package com.estore.network;

import com.estore.model.Order;
import com.estore.model.OrderService;
import com.estore.model.Product;
import com.estore.model.User;
import com.estore.service.*;

import java.io.*;
import java.net.*;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import com.estore.service.UserService;

public class EStoreClient {
    private static final String SERVER_HOST = "localhost"; // 服务器地址
    private static final int SERVER_PORT = 8888; // 服务器端口

    private User currentUser; // 当前登录用户
    private final UserService userService = new UserService();
    private final ProductService productService = new ProductService();
    private final OrderService orderService = new OrderService(productService);
    private final CategoryService categoryService = new CategoryService(productService);
    private final ReportService reportService = new ReportService(orderService, productService, userService);
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new ConcurrentHashMap<>();
    private final Map<String, Double> productPriceAtAddTime = new ConcurrentHashMap<>();

    private final Scanner scanner = new Scanner(System.in);


    private void loadFavoritesFromFile() {
        if (currentUser == null) {
            return;
        }

        try {
            String favoritesFileName = "favorites_%s.dat".formatted(currentUser.getUserId());
            File favoritesFile = new File(favoritesFileName);

            if (favoritesFile.exists()) {
                try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(favoritesFileName))) {
                    @SuppressWarnings("unchecked")
                    Set<String> loadedFavorites = (Set<String>) ois.readObject();
                    userFavorites.put(currentUser.getUserId(), loadedFavorites);
                    System.out.println("收藏夹数据加载成功");
                }
            } else {
                // 文件不存在，初始化空地收藏夹
                userFavorites.putIfAbsent(currentUser.getUserId(), new HashSet<>());
                System.out.println("未找到收藏夹数据文件，初始化空收藏夹");
            }
        } catch (Exception e) {
            System.out.printf("收藏夹数据加载失败: %s%n", e.getMessage());
            // 出错时初始化空地收藏夹
            userFavorites.putIfAbsent(currentUser.getUserId(), new HashSet<>());
        }
    }
    private void saveFavoritesToFile() {
        if (currentUser == null) {
            return;
        }

        try {
            String favoritesFileName = "favorites_%s.dat".formatted(currentUser.getUserId());
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(favoritesFileName))) {
                oos.writeObject(userFavorites.getOrDefault(currentUser.getUserId(), new HashSet<>()));
            }
            System.out.println("收藏夹数据保存成功");
        } catch (Exception e) {
            System.err.printf("保存收藏夹数据时发生错误: %s%n", e.getMessage());
        }
    }

private void exitApplication() {
    System.out.println("正在保存数据...");
    try {
        // 保存购物车数据
        if (currentUser != null) {
            saveCartToFile();
        }

        // 保存商品数据
        productService.saveData();

        // 用户数据现在由服务器端保存，客户端不需要保存

        // 保存订单数据
        orderService.saveData();

        System.out.println("所有数据保存完成！");
    } catch (Exception e) {
        System.err.printf("保存数据时发生错误: %s%n", e.getMessage());
    }

    // 不调用 System.exit(0)，而是返回到主循环
    System.out.println("数据已保存，返回主菜单。");
}

/**
 * 从文件加载订单数据
 */
private void loadOrderData() {
    try {
        orderService.loadData();
        System.out.println("订单数据加载成功");
    } catch (Exception e) {
        System.out.printf("订单数据加载失败: %s%n", e.getMessage());
    }
}

/**
 * 通过网络获取订单详情
 * @param orderId 订单ID
 * @return 订单对象，如果未找到返回null
 */
private Order findOrderByIdViaNetwork(String orderId) {
    try {
        // 获取所有订单
        List<Order> allOrders = getAllOrdersViaNetwork();
        if (allOrders != null) {
            // 查找指定ID的订单
            for (Order order : allOrders) {
                if (order.getOrderId().equals(orderId)) {
                    return order;
                }
            }
        }
    } catch (Exception e) {
        System.err.printf("获取订单详情失败: %s%n", e.getMessage());
    }
    return null;
}


// 在 ConsoleShop 类中添加以下字段声明（在其他字段声明附近）
// 记录商品添加时的价格，key是购物车键，value是价格

public void start() {
    loadOrderData();
    System.out.println("欢迎使用商城系统！");

    // 登录或注册循环
    while (currentUser == null) {  // 当用户未登录时循环显示登录菜单
        showLoginMenu();
        int choice = readIntInput();

        switch (choice) {
            case 1:
                login();
                break;
            case 2:
                register();
                break;
            case 3:
                System.out.println("感谢使用，再见！");
                scanner.close();
                return; // 只有选择退出(3)时才真正退出程序
            default:
                System.out.println("无效的选项，请重新输入！");
        }
    }

    // 用户已登录，显示主菜单
    showMainMenu();
}



private void showMainMenu() {
    while (currentUser != null) {  // 当用户登录时循环显示菜单
        if (currentUser.getRole() == User.UserRole.ADMIN) {
            showAdminMenu();
            int choice = readIntInput();
            handleAdminMenuChoice(choice);
        } else {
            showCustomerMenu();
            int choice = readIntInput();
            handleCustomerMenuChoice(choice);
        }
    }
    // 当 currentUser 变为 null 时（logout 被调用），自动回到登录循环
}




    private void showLoginMenu() {
        System.out.println("\n==== 用户登录 ====");
        System.out.println("1. 登录");
        System.out.println("2. 注册");
        System.out.println("3. 退出");
        System.out.print("请输入您的选择: ");
    }

 // 修改 login 方法
// 修改 login 方法
// 修改 login 方法
// 修改 login 方法
 private void login() {
     System.out.print("请输入用户名: ");
     String username = scanner.nextLine();
     String password = readPassword("请输入密码: "); // 使用 readPassword 方法隐藏密码输入

     User user = loginViaNetwork(username, password);
     if (user != null) {
         currentUser = user;
         System.out.printf("登录成功！欢迎您，%s！%n", user.getUsername());

         // 登录成功后加载购物车数据
         loadCartFromFile();

         // 加载收藏夹数据
         loadFavoritesFromFile();

         // 如果是管理员，检查超时订单
         if (user.getRole() == User.UserRole.ADMIN) {
             System.out.println("正在检查超时订单...");
             checkAndCancelTimeoutOrders();
         }
     } else {
         System.out.println("登录失败！用户名或密码错误。");
     }
 }



/**
 * 检查并自动取消超时订单
 */
private void checkAndCancelTimeoutOrders() {
    // 获取所有待支付订单（通过网络）
    List<Order> allOrders = getAllOrdersViaNetwork();
    List<Order> pendingOrders = allOrders.stream()
        .filter(order -> order.getStatus() == Order.OrderStatus.PENDING_PAYMENT)
        .toList();
    
    java.time.LocalDateTime timeoutThreshold = java.time.LocalDateTime.now().minusMinutes(30); // 30分钟超时

    int cancelledCount = 0;
    for (Order order : pendingOrders) {
        if (order.getCreateTime().isBefore(timeoutThreshold)) {
            Order updatedOrder = updateOrderStatusViaNetwork(order.getOrderId(), Order.OrderStatus.CANCELLED);
            if (updatedOrder != null) {
                cancelledCount++;
                System.out.printf("订单 %s 因超时未支付已自动取消%n", order.getOrderId());

                // 恢复库存（服务器端已处理，此处仅显示信息）
                restoreProductStock(order);
            }
        }
    }

    if (cancelledCount > 0) {
        System.out.printf("共自动取消 %d 个超时订单%n", cancelledCount);
    }
}


// 修改 register 方法
private void register() {
    System.out.print("请输入用户名: ");
    String username = scanner.nextLine();
    String password = readPassword("请输入密码: ");
    System.out.print("请输入邮箱: ");
    String email = scanner.nextLine();

    // 验证邮箱格式
    if (isValidEmail(email)) {
        System.out.println("注册失败: 邮箱格式不正确");
        return;
    }

    User user = registerViaNetwork(username, password, email);
    if (user != null) {
        System.out.printf("注册成功！您的用户ID是: %s%n", user.getUserId());
    } else {
        System.out.println("注册失败，请检查输入信息");
    }
}


private void showCustomerMenu() {
    System.out.println("\n==== 欢迎来到商城 ====");
    System.out.println("1. 浏览所有商品");
    System.out.println("2. 添加商品到购物车");
    System.out.println("3. 查看购物车");
    System.out.println("4. 自定义排序浏览商品");
    System.out.println("5. 结算购买");
    System.out.println("6. 搜索商品");
    System.out.println("7. 订单管理");
    System.out.println("8. 按分类浏览商品");
    System.out.println("9. 个人信息管理");
    System.out.println("10. 我的收藏夹");
    System.out.println("11. 退出系统");
    System.out.println("0. 退出登录");
    System.out.print("请输入您的选择: ");
}



   // 修改 showAdminMenu 方法，在适当位置添加标签管理选项
   private void showAdminMenu() {
       System.out.println("\n==== 管理员控制台 ====");
       System.out.println("1. 浏览所有商品");
       System.out.println("2. 添加商品到购物车");
       System.out.println("3. 查看购物车");
       System.out.println("4. 自定义排序浏览商品");
       System.out.println("5. 结算购买");
       System.out.println("6. 搜索商品");
       System.out.println("7. 修改商品信息");
       System.out.println("8. 订单管理");
       System.out.println("9. 商品分类管理");
       System.out.println("10. 按分类浏览商品");
       System.out.println("11. 用户管理");
       System.out.println("12. 个人信息管理");
       System.out.println("13. 处理所有待支付订单");
       System.out.println("14. 商品标签管理");
       System.out.println("15. 数据统计与报表");
       System.out.println("16.用户订单管理 ");
       System.out.println("17. 订单有效期管理");
       System.out.println("18. 退出系统");
       System.out.println("0. 退出登录");
       System.out.print("请输入您的选择: ");
   }

    private void manageReports() {
        while (true) {
            System.out.println("\n--- 数据统计与报表 ---");
            System.out.println("1. 销售数据统计");
            System.out.println("2. 用户行为分析");
            System.out.println("3. 商品销售排行榜");
            System.out.println("4. 财务报表生成");
            System.out.println("5. 最近7天销售趋势");
            System.out.println("0. 返回上级菜单");
            System.out.print("请输入您的选择: ");

            int choice = readIntInput();

            switch (choice) {
                case 1:
                    generateSalesReport();
                    break;
                case 2:
                    generateUserBehaviorAnalysis();
                    break;
                case 3:
                    generateProductRanking();
                    break;
                case 4:
                    generateFinancialReport();
                    break;
                case 5:
                    viewRecent7DaysTrend();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效的选项！");
            }

            // 等待用户按键后继续
            System.out.println("\n按回车键继续...");
            scanner.nextLine();
        }
    }
// In the generateSalesReport method, replace the date input section with:
private void generateSalesReport() {
    try {
        System.out.println("\n--- 销售数据统计 ---");
        System.out.println("请输入统计年份和月份:");
        System.out.print("年份 (如 2024): ");
        int year = readIntInput();

        System.out.print("月份 (1-12): ");
        int month = readIntInput();

        System.out.print("开始日期 (1-31): ");
        int startDay = readIntInput();

        System.out.print("结束日期 (1-31): ");
        int endDay = readIntInput();

        // 验证月份和日期
        if (month < 1 || month > 12) {
            System.out.println("错误：月份必须在1-12之间");
            return;
        }

        int maxDay = java.time.YearMonth.of(year, month).lengthOfMonth();
        if (startDay < 1 || startDay > maxDay) {
            System.out.printf("错误：开始日期必须在1-%d之间%n", maxDay);
            return;
        }

        if (endDay < 1 || endDay > maxDay) {
            System.out.printf("错误：结束日期必须在1-%d之间%n", maxDay);
            return;
        }

        if (startDay > endDay) {
            System.out.println("错误：开始日期不能晚于结束日期");
            return;
        }

        LocalDate startDate = LocalDate.of(year, month, startDay);
        LocalDate endDate = LocalDate.of(year, month, endDay);

        // 通过网络请求获取销售报告
        Object report = sendReportRequest("GENERATE SALES REPORT", startDate, endDate);
        if (report instanceof com.estore.service.ReportService.SalesReport) {
            System.out.println(report);
        } else {
            System.out.printf("生成销售报告失败: %s%n", report);
        }
    } catch (Exception e) {
        System.out.printf("输入格式错误或查询失败：%s%n", e.getMessage());
    }
}

    // 修改 generateUserBehaviorAnalysis 方法
    private void generateUserBehaviorAnalysis() {
        try {
            System.out.println("\n--- 用户行为分析 ---");
            System.out.println("请输入统计年份和月份:");
            System.out.print("年份 (如 2024): ");
            int year = readIntInput();

            System.out.print("月份 (1-12): ");
            int month = readIntInput();

            System.out.print("开始日期 (1-31): ");
            int startDay = readIntInput();

            System.out.print("结束日期 (1-31): ");
            int endDay = readIntInput();

            // 验证月份和日期
            if (month < 1 || month > 12) {
                System.out.println("错误：月份必须在1-12之间");
                return;
            }

            int maxDay = java.time.YearMonth.of(year, month).lengthOfMonth();
            if (startDay < 1 || startDay > maxDay) {
                System.out.printf("错误：开始日期必须在1-%d之间%n", maxDay);
                return;
            }

            if (endDay < 1 || endDay > maxDay) {
                System.out.printf("错误：结束日期必须在1-%d之间%n", maxDay);
                return;
            }

            if (startDay > endDay) {
                System.out.println("错误：开始日期不能晚于结束日期");
                return;
            }

            LocalDate startDate = LocalDate.of(year, month, startDay);
            LocalDate endDate = LocalDate.of(year, month, endDay);

            // 通过网络请求获取用户行为分析报告
            Object report = sendReportRequest("GENERATE USER BEHAVIOR ANALYSIS", startDate, endDate);
            if (report instanceof com.estore.service.ReportService.UserBehaviorAnalysis) {
                System.out.println(report);
            } else {
                System.out.printf("生成用户行为分析报告失败: %s%n", report);
            }
        } catch (Exception e) {
            System.out.printf("输入格式错误或查询失败：%s%n", e.getMessage());
        }
    }
    // 修改 generateProductRanking 方法
    private void generateProductRanking() {
        try {
            System.out.println("\n--- 商品销售排行榜 ---");
            System.out.println("1. 按销售数量排行");
            System.out.println("2. 按销售额排行");
            System.out.print("请选择排行方式 (默认为1): ");

            int sortChoice = 1;
            try {
                sortChoice = readIntInput();
                if (sortChoice != 1 && sortChoice != 2) {
                    sortChoice = 1;
                }
            } catch (Exception e) {
                System.out.println("输入格式错误，使用默认排行方式。");
            }

            System.out.print("请输入排行榜长度 (默认10): ");
            int limit = readIntInput();
            if (limit <= 0) {
                limit = 10;
            }

            System.out.println("请输入统计年份和月份:");
            System.out.print("年份 (如 2024): ");
            int year = readIntInput();

            System.out.print("月份 (1-12): ");
            int month = readIntInput();

            System.out.print("开始日期 (1-31): ");
            int startDay = readIntInput();

            System.out.print("结束日期 (1-31): ");
            int endDay = readIntInput();

            // 验证月份和日期
            if (month < 1 || month > 12) {
                System.out.println("错误：月份必须在1-12之间");
                return;
            }

            int maxDay = java.time.YearMonth.of(year, month).lengthOfMonth();
            if (startDay < 1 || startDay > maxDay) {
                System.out.printf("错误：开始日期必须在1-%d之间%n", maxDay);
                return;
            }

            if (endDay < 1 || endDay > maxDay) {
                System.out.printf("错误：结束日期必须在1-%d之间%n", maxDay);
                return;
            }

            if (startDay > endDay) {
                System.out.println("错误：开始日期不能晚于结束日期");
                return;
            }

            LocalDate startDate = LocalDate.of(year, month, startDay);
            LocalDate endDate = LocalDate.of(year, month, endDay);

            // 通过网络请求获取商品销售排行榜
            Object report = sendProductRankingRequest(limit, startDate, endDate);
            if (report instanceof List) {
                @SuppressWarnings("unchecked")
                List<com.estore.service.ReportService.ProductRanking> rankings =
                        (List<com.estore.service.ReportService.ProductRanking>) report;

                // 根据选择的排序方式进行排序
                if (sortChoice == 2) {
                    // 按销售额排序
                    rankings.sort((r1, r2) -> Double.compare(r2.getTotalSales(), r1.getTotalSales()));
                } else {
                    // 按销售数量排序 (默认)
                    rankings.sort((r1, r2) -> Integer.compare(r2.getSoldQuantity(), r1.getSoldQuantity()));
                }

                System.out.println("\n=== 商品销售排行榜 ===");
                String sortType = sortChoice == 2 ? "销售额" : "销售数量";
                System.out.printf("按%s排行 (TOP %d):\n", sortType, limit);
                for (int i = 0; i < rankings.size(); i++) {
                    com.estore.service.ReportService.ProductRanking ranking = rankings.get(i);
                    System.out.printf("%d. %s (%s) - 销量: %d 件, 销售额: %.2f 元\n",
                            i + 1, ranking.getProductName(), ranking.getProductId(),
                            ranking.getSoldQuantity(), ranking.getTotalSales());
                }
            } else {
                System.out.printf("生成商品销售排行榜失败: %s%n", report);
            }
        } catch (Exception e) {
            System.out.printf("输入格式错误或查询失败：%s%n", e.getMessage());
        }
    }

    // 修改 generateFinancialReport 方法
    private void generateFinancialReport() {
        try {
            System.out.println("\n--- 财务报表生成 ---");
            System.out.println("请输入统计年份和月份:");
            System.out.print("年份 (如 2024): ");
            int year = readIntInput();

            System.out.print("月份 (1-12): ");
            int month = readIntInput();

            System.out.print("开始日期 (1-31): ");
            int startDay = readIntInput();

            System.out.print("结束日期 (1-31): ");
            int endDay = readIntInput();

            // 验证月份和日期
            if (month < 1 || month > 12) {
                System.out.println("错误：月份必须在1-12之间");
                return;
            }

            int maxDay = java.time.YearMonth.of(year, month).lengthOfMonth();
            if (startDay < 1 || startDay > maxDay) {
                System.out.printf("错误：开始日期必须在1-%d之间%n", maxDay);
                return;
            }

            if (endDay < 1 || endDay > maxDay) {
                System.out.printf("错误：结束日期必须在1-%d之间%n", maxDay);
                return;
            }

            if (startDay > endDay) {
                System.out.println("错误：开始日期不能晚于结束日期");
                return;
            }

            LocalDate startDate = LocalDate.of(year, month, startDay);
            LocalDate endDate = LocalDate.of(year, month, endDay);

            // 通过网络请求获取财务报告
            Object report = sendReportRequest("GENERATE FINANCIAL REPORT", startDate, endDate);
            if (report instanceof com.estore.service.ReportService.FinancialReport) {
                System.out.println(report);
            } else {
                System.out.printf("生成财务报表失败: %s%n", report);
            }
        } catch (Exception e) {
            System.out.printf("输入格式错误或查询失败：%s%n", e.getMessage());
        }
    }
    // 添加网络请求方法
    private Object sendReportRequest(String requestType, LocalDate startDate, LocalDate endDate) {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 发送请求
            String request = String.format("%s:%s:%s", requestType, startDate.toString(), endDate.toString());
            output.writeObject(request);
            output.flush();

            // 读取响应
            return input.readObject();
        } catch (IOException | ClassNotFoundException e) {
            return "网络错误: %s".formatted(e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭连接时出错: %s%n", e.getMessage());
                }
            }
        }
    }
    private Object sendProductRankingRequest(int limit, LocalDate startDate, LocalDate endDate) {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 发送请求
            String request = String.format("%s:%d:%s:%s", "GENERATE PRODUCT RANKING", limit, startDate.toString(), endDate.toString());
            output.writeObject(request);
            output.flush();

            // 读取响应
            return input.readObject();
        } catch (IOException | ClassNotFoundException e) {
            return "网络错误: %s".formatted(e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭连接时出错: %s%n", e.getMessage());
                }
            }
        }
    }

    /**
     * 检查订单是否过期
     * @param orderId 订单ID
     * @return 订单状态信息
     */
    private String checkOrderExpiredViaNetwork(String orderId) {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 发送请求
            String request = "CHECK ORDER EXPIRED:%s".formatted(orderId);
            output.writeObject(request);
            output.flush();

            // 读取响应
            return (String) input.readObject();
        } catch (IOException | ClassNotFoundException e) {
            return "网络错误: %s".formatted(e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭连接时出错: %s%n", e.getMessage());
                }
            }
        }
    }

    /**
     * 手动清理过期订单
     * @return 清理结果
     */
    private String cleanupExpiredOrdersViaNetwork() {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 发送请求
            output.writeObject("CLEANUP EXPIRED ORDERS");
            output.flush();

            // 读取响应
            return (String) input.readObject();
        } catch (IOException | ClassNotFoundException e) {
            return "网络错误: %s".formatted(e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭连接时出错: %s%n", e.getMessage());
                }
            }
        }
    }

    /**
     * 获取即将过期的订单
     * @return 即将过期的订单列表
     */
    @SuppressWarnings("unchecked")
    private List<Order> getOrdersAboutToExpireViaNetwork() {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 发送请求
            output.writeObject("GET ORDERS ABOUT TO EXPIRE");
            output.flush();

            // 读取响应
            Object response = input.readObject();
            if (response instanceof List) {
                return (List<Order>) response;
            } else {
                System.out.printf("获取即将过期订单失败: %s%n", response);
                return new ArrayList<>();
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.printf("网络错误: %s%n", e.getMessage());
            return new ArrayList<>();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭连接时出错: %s%n", e.getMessage());
                }
            }
        }
    }
    private void viewRecent7DaysTrend() {
        List<ReportService.DailySalesTrend> trendList = reportService.getRecent7DaysSalesTrend();
        System.out.println("\n=== 最近7天销售趋势 ===");
        for (ReportService.DailySalesTrend trend : trendList) {
            System.out.println(trend);
        }
    }

 /**
 * 管理员功能：查看并处理所有待支付订单
 */
private void manageAllPendingOrders() {
    // 获取所有待支付订单（通过网络）
    List<Order> allOrders = getAllOrdersViaNetwork();
    List<Order> allPendingOrders = allOrders.stream()
        .filter(order -> order.getStatus() == Order.OrderStatus.PENDING_PAYMENT)
        .toList();

    if (allPendingOrders.isEmpty()) {
        System.out.println("没有待支付的订单。");
        return;
    }

    // 显示所有待支付订单
    System.out.println("\n--- 所有待支付订单 ---");
    double totalAmount = 0.0;
    for (Order order : allPendingOrders) {
        System.out.printf("订单ID: %s | 用户ID: %s | 金额: ¥%s%n",
            order.getOrderId(), order.getUserId(), String.format("%.2f", order.getTotalPrice()));
        totalAmount += order.getTotalPrice();
    }
    System.out.printf("总金额: ¥%s%n", String.format("%.2f", totalAmount));

    System.out.print("确认支付以上所有订单吗？(y/n): ");
    String confirm = scanner.nextLine();

    if (!"y".equalsIgnoreCase(confirm)) {
        System.out.println("已取消支付。");
        return;
    }

    // 支付所有待支付订单
    boolean allSuccess = true;
    for (Order order : allPendingOrders) {
        Order updatedOrder = updateOrderStatusViaNetwork(order.getOrderId(), Order.OrderStatus.PAID);
        if (updatedOrder != null) {
            System.out.printf("订单 %s (用户: %s) 已支付成功！%n", order.getOrderId(), order.getUserId());
            
            // 为该订单的用户增加积分（按消费：积分=10：1的比例）
            double pointsToAdd = order.getTotalPrice() / 10.0; // 消费10元增加1积分
            User updatedUser = addPointsViaNetwork(order.getUserId(), pointsToAdd);
            if (updatedUser != null) {
                System.out.printf("🎉 用户 %s 获得 %.1f 积分！当前总积分: %d%n", 
                    order.getUserId(), pointsToAdd, updatedUser.getPoints());
            }
        } else {
            System.out.printf("订单 %s (用户: %s) 支付失败！%n", order.getOrderId(), order.getUserId());
            allSuccess = false;
        }
    }

    if (allSuccess) {
        System.out.println("所有订单支付完成！");

        // 询问是否立即将订单设为配送中状态
        System.out.print("是否立即将所有已支付订单设为配送中状态？(y/n): ");
        String shipConfirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(shipConfirm)) {
            for (Order order : allPendingOrders) {
                Order updatedOrder = updateOrderStatusViaNetwork(order.getOrderId(), Order.OrderStatus.SHIPPING);
                if (updatedOrder != null) {
                    System.out.printf("订单 %s (用户: %s) 已切换到配送中状态！%n", order.getOrderId(), order.getUserId());
                } else {
                    System.out.printf("订单 %s (用户: %s) 状态更新失败！%n", order.getOrderId(), order.getUserId());
                }
            }
            System.out.println("所有订单已进入配送流程！");
        } else {
            System.out.println("订单已支付但尚未配送，请前往订单管理手动设置配送状态。");
        }
    } else {
        System.out.println("部分订单支付失败，请检查订单状态。");
    }
}


//    private void logout() {
//        currentUser = null;
//        System.out.println("已退出登录！");
//        start(); // 重新开始登录流程
//    }

    // 个人信息管理功能
// 修改 manageUserInfo 方法，完善用户输入处理
/**
 * 个人信息管理功能
 */
private void manageUserInfo() {
    while (true) {
        System.out.println("\n--- 个人信息管理 ---");
        System.out.println("当前用户信息:");
        System.out.println(currentUser.toString());

        System.out.println("\n请选择操作:");
        System.out.println("1. 修改个人信息");
        System.out.println("2. 修改密码");
        System.out.println("0. 返回上级菜单");
        System.out.print("请输入您的选择: ");

        int choice = readIntInput(); // 添加这行来读取用户输入

        switch (choice) {
            case 1:
                updateUserInfo();
                break;
            case 2:
                changePassword();
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选项！");
        }

        // 等待用户按键后继续
        System.out.println("\n按回车键继续...");
        scanner.nextLine();
    }
}


// 修改 updateUserInfo 方法
/**
 * 更新用户信息
 */
private void updateUserInfo() {
    System.out.println("\n--- 修改个人信息 ---");
    System.out.printf("请输入新的邮箱(当前: %s): ", currentUser.getEmail());
    String email = scanner.nextLine();

    // 验证邮箱格式
    if (isValidEmail(email)) {
        System.out.println("邮箱格式不正确，更新失败！");
        return;
    }

    System.out.printf("请输入新的电话(当前: %s): ", currentUser.getPhone());
    String phone = scanner.nextLine();
    System.out.printf("请输入新的地址(当前: %s): ", currentUser.getAddress());
    String address = scanner.nextLine();

    User updatedUser = updateUserInfoViaNetwork(currentUser.getUserId(), email, phone, address);
    if (updatedUser != null) {
        currentUser = updatedUser; // 更新当前用户信息
        System.out.println("个人信息更新成功！");
        System.out.println("更新后的信息:");
        System.out.println(currentUser);
    } else {
        System.out.println("更新失败！");
    }
}

/**
 * 修改密码
 */
private void changePassword() {
    System.out.println("\n--- 修改密码 ---");
    String oldPassword = readPassword("请输入当前密码: ");
    String newPassword = readPassword("请输入新密码: ");
    System.out.print("请再次输入新密码: ");
    String confirmPassword = scanner.nextLine();

    if (!newPassword.equals(confirmPassword)) {
        System.out.println("两次输入的新密码不一致！");
        return;
    }

    boolean success = changePasswordViaNetwork(currentUser.getUserId(), oldPassword, newPassword);
    if (success) {
        currentUser.setPassword(newPassword); // 更新当前用户密码
        System.out.println("密码修改成功！");
    } else {
        System.out.println("密码修改失败！原密码错误。");
    }
}


    // 用户管理功能（仅管理员可见）
// 在 ConsoleShop.java 中添加或修改以下方法

/**
 * 用户管理功能（仅管理员可见）
 */
private void manageUsers() {
    while (true) {
        System.out.println("\n--- 用户管理 ---");
        System.out.println("1. 查看所有用户");
        System.out.println("2. 删除用户");
        System.out.println("3. 修改用户角色");
        System.out.println("4. 调整用户积分");
        System.out.println("5. 解锁用户账户");
        System.out.println("6. 重置指定用户密码为123");
        System.out.println("0. 返回上级菜单");
        System.out.print("请输入您的选择: ");

        int choice = readIntInput();

        switch (choice) {
            case 1:
                viewAllUsers();
                break;
            case 2:
                deleteUser();
                break;
            case 3:
                changeUserRole();
                break;
            case 4:
                adjustUserPoints();
                break;
            case 5:
                unlockUserAccount();
                break;
            case 6:
                resetUserPassword();
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选项！");
        }

        // 等待用户按键后继续
        System.out.println("\n按回车键继续...");
        scanner.nextLine();
    }
}
/**
 * 重置指定用户密码为123（管理员功能）
 */
private void resetUserPassword() {
    // 先获取所有用户列表
    List<User> users = getAllUsersViaNetwork();
    if (users == null || users.isEmpty()) {
        System.out.println("获取用户列表失败或用户列表为空");
        return;
    }

    System.out.println("\n--- 所有用户列表 ---");
    System.out.println("编号 | 用户ID | 用户名 | 角色");
    System.out.println("----------------------------------------");

    Map<Integer, User> userMap = new HashMap<>();
    int index = 1;
    for (User user : users) {
        userMap.put(index, user);
        System.out.printf("%d    | %s | %s | %s%n",
            index, user.getUserId(), user.getUsername(), user.getRole());
        index++;
    }

    System.out.print("\n请选择要重置密码的用户编号 (0取消): ");
    int choice = readIntInput();

    if (choice == 0) {
        System.out.println("操作已取消。");
        return;
    }

    if (!userMap.containsKey(choice)) {
        System.out.println("无效的用户编号！");
        return;
    }

    User selectedUser = userMap.get(choice);
    System.out.printf("您选择的用户: %s (%s)%n", selectedUser.getUsername(), selectedUser.getUserId());

    System.out.print("确认将该用户密码重置为'123'吗？(y/n): ");
    String confirm = scanner.nextLine();

    if (!"y".equalsIgnoreCase(confirm)) {
        System.out.println("操作已取消。");
        return;
    }

    // 发送重置密码请求并处理响应
    try {
        String result = sendResetUserPasswordRequest(selectedUser.getUserId());
        if (result.contains("失败")) {
            System.out.println("密码重置失败！");
        } else {
            System.out.printf("重置密码成功: %s%n", result);
        }
    } catch (Exception e) {
        System.out.printf("重置密码失败: %s%n", e.getMessage());
    }
}

/**
 * 发送重置用户密码请求
 * @param userId 用户ID
 * @return 服务器响应消息
 */
private String sendResetUserPasswordRequest(String userId) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送重置用户密码的请求
        String request = "RESET USER PASSWORD:%s".formatted(userId);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof String) {
            return (String) response;
        } else {
            return "服务器返回了意外的响应类型";
        }
    } catch (IOException | ClassNotFoundException e) {
        return "网络错误: %s".formatted(e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
}

    /**
 * 修改用户角色
 */
private void changeUserRole() {
    System.out.print("请输入要修改的用户ID: ");
    String userId = scanner.nextLine();

    User user = findUserByIdViaNetwork(userId);
    if (user == null) {
         System.out.println("用户不存在！");
         return;
    }

    if (userId.equals("admin")) {
        System.out.println("不能修改管理员角色！");
        return;
    }

    System.out.printf("当前用户角色：%s%n", user.getRole());
    System.out.println("可选角色：");
    System.out.println("1. 普通用户");
    System.out.println("2. VIP用户");
    System.out.print("请选择新角色: ");

    int roleChoice = readIntInput();
    User.UserRole newRole;
    switch (roleChoice) {
        case 1:
            newRole = User.UserRole.CUSTOMER;
            break;
        case 2:
            newRole = User.UserRole.VIP;
            break;
        default:
            System.out.println("无效的选择！");
            return;
    }

    boolean success = updateUserRoleViaNetwork(userId, newRole);
    if (success) {
        System.out.println("用户角色修改成功！");
    } else {
        System.out.println("用户角色修改失败！");
    }
}

    /**
 * 调整用户积分
 */
private void adjustUserPoints() {
    System.out.print("请输入用户ID: ");
    String userId = scanner.nextLine();

    User user = findUserByIdViaNetwork(userId);
    if (user == null) {
        System.out.println("用户不存在！");
        return;
    }

    System.out.printf("用户当前积分：%d%n", user.getPoints());
    System.out.print("请输入积分调整值（正数增加，负数减少）: ");
    int points;
    try {
        points = scanner.nextInt();
        scanner.nextLine(); // 消费换行符
    } catch (Exception e) {
        scanner.nextLine(); // 清除非法输入
        System.out.println("输入格式错误！");
        return;
    }

    int originalPoints = user.getPoints();
    User updatedUser = updateUserPointsViaNetwork(userId, points);
    if (updatedUser != null) {
        System.out.printf("积分调整成功！%n");
        System.out.printf("积分变动: %d -> %d (%+d)%n", originalPoints, updatedUser.getPoints(), points);
        System.out.printf("用户当前积分：%d，角色：%s%n",
                         updatedUser.getPoints(), updatedUser.getRole());
    } else {
        System.out.println("积分调整失败！");
    }
}


/**
 * 解锁用户账户
 */
private void unlockUserAccount() {
    System.out.print("请输入要解锁的用户ID: ");
    String userId = scanner.nextLine();

    boolean success = unlockUserViaNetwork(userId);
    if (success) {
        System.out.println("用户账户解锁成功！");
    } else {
        System.out.println("用户账户解锁失败！");
    }
}

// 修改 handleCustomerMenuChoice 方法，在最开始添加会话检查
private void handleCustomerMenuChoice(int choice) {
    switch (choice) {
        case 1:
            browseProducts();
            break;
        case 2:
            addToCart();
            break;
        case 3:
            viewCart();
            break;
        case 4:
            showSortedProducts();
            break;
        case 5:
            // 结算购买功能：先创建订单，再支付订单
            createOrderFromCart();    // 创建新订单
            payPendingOrders();       // 支付待支付订单
            break;
        case 6:
            searchProducts();
            break;
        case 7:
            customerOrderManagement();
            break;
        case 8:
            browseProductsByCategory();
            break;
        case 9:
            manageUserInfo();
            break;
        case 10:
            manageFavorites();
            break;
        case 11: // 退出登录选项
            exitApplication();
            break;
        case 0:
            logout();
            break;
        default:
            System.out.println("无效的选项，请重新输入！");
    }
}

// 在 ConsoleShop.java 中添加以下方法

    /**
 * 商品标签管理功能
 */
private void manageProductTags() {
    System.out.print("请输入商品ID: ");
    String productId = scanner.nextLine();

    Product product = getProductByIdViaNetwork(productId);
    if (product == null) {
        System.out.println("未找到该商品！");
        return;
    }

    while (true) {
        System.out.println("\n--- 商品标签管理 ---");
        System.out.printf("商品信息: %s%n", product);
        System.out.printf("当前标签: %s%n", Objects.requireNonNull(product).getTags() != null ? product.getTags() : "无标签");
        System.out.println("1. 添加标签");
        System.out.println("2. 移除标签");
        System.out.println("3. 清空所有标签");
        System.out.println("4. 批量设置标签");
        System.out.println("0. 返回上级菜单");
        System.out.print("请输入您的选择: ");

        int choice = readIntInput();

        switch (choice) {
            case 1:
                addTagToProduct(productId, product);
                break;

            case 2:
                removeTagFromProduct(productId, product);
                break;

            case 3:
                clearAllTags(productId, product);
                break;

            case 4:
                batchSetTags(productId, product);
                break;

            case 0:
                return;

            default:
                System.out.println("无效选择，请重新输入！");
        }

        // 从网络重新获取商品信息以反映最新状态
        product = getProductByIdViaNetwork(productId);
    }
}

/**
 * 为商品添加标签
 */
private void addTagToProduct(String productId, Product product) {
    // 检查商品是否存在
    if (product == null) {
        System.out.println("商品不存在！");
        return;
    }

    System.out.print("请输入要添加的标签: ");
    String newTag = scanner.nextLine().trim();

    if (newTag.isEmpty()) {
        System.out.println("标签不能为空！");
        return;
    }

    if (addTagToProductViaNetwork(productId, newTag)) {
        System.out.println("标签添加成功！");
        // 从网络重新获取商品以显示更新后的标签
        Product updatedProduct = getProductByIdViaNetwork(productId);
        if (updatedProduct != null) {
            System.out.printf("更新后的标签: %s%n", updatedProduct.getTags());
        }
    } else {
        System.out.println("标签添加失败！");
    }
}



/**
 * 从商品中移除标签
 */
private void removeTagFromProduct(String productId, Product product) {
    // 检查商品是否存在
    if (product == null) {
        System.out.println("商品不存在！");
        return;
    }

    if (product.getTags() == null || product.getTags().isEmpty()) {
        System.out.println("该商品没有标签可移除！");
        return;
    }

    System.out.print("请输入要移除的标签: ");
    String tagToRemove = scanner.nextLine().trim();

    if (tagToRemove.isEmpty()) {
        System.out.println("标签不能为空！");
        return;
    }

    if (removeTagFromProductViaNetwork(productId, tagToRemove)) {
        System.out.println("标签移除成功！");
        // 从网络重新获取商品以显示更新后的标签
        Product updatedProduct = getProductByIdViaNetwork(productId);
        if (updatedProduct != null) {
            System.out.printf("更新后的标签: %s%n", updatedProduct.getTags());
        }
    } else {
        System.out.println("标签移除失败！可能该标签不存在。");
    }
}

/**
 * 清空商品的所有标签
 */
private void clearAllTags(String productId, Product product) {
    // 检查商品是否存在
    if (product == null) {
        System.out.println("商品不存在！");
        return;
    }

    if (product.getTags() == null || product.getTags().isEmpty()) {
        System.out.println("该商品没有标签可清空！");
        return;
    }

    System.out.print("确认要清空所有标签吗？(y/n): ");
    String confirm = scanner.nextLine().trim();

    if ("y".equalsIgnoreCase(confirm)) {
        Set<String> emptyTags = new HashSet<>();
        Product updatedProduct = updateProductTagsViaNetwork(productId, emptyTags);
        if (updatedProduct != null) {
            System.out.println("所有标签已清空！");
            System.out.printf("更新后的标签: %s%n", updatedProduct.getTags());
        } else {
            System.out.println("清空标签失败！");
        }
    } else {
        System.out.println("操作已取消。");
    }
}


/**
 * 批量设置商品标签
 */
private void batchSetTags(String productId, Product product) {
    // 检查商品是否存在
    if (product == null) {
        System.out.println("商品不存在！");
        return;
    }

    System.out.println("请输入新的标签列表(用逗号分隔): ");
    String tagsInput = scanner.nextLine();

    if (tagsInput.trim().isEmpty()) {
        System.out.println("标签列表不能为空！");
        return;
    }

    Set<String> newTags = new HashSet<>();
    String[] tagsArray = tagsInput.split(",");

    // 解析并清理标签
    for (String tag : tagsArray) {
        String trimmedTag = tag.trim();
        if (!trimmedTag.isEmpty()) {
            newTags.add(trimmedTag);
        }
    }

    // 检查是否有有效标签
    if (newTags.isEmpty()) {
        System.out.println("未找到有效的标签！");
        return;
    }

    Product updatedProduct = updateProductTagsViaNetwork(productId, newTags);
    if (updatedProduct != null) {
        System.out.println("标签更新成功！");
        System.out.printf("更新后的标签: %s%n", updatedProduct.getTags());
    } else {
        System.out.println("标签更新失败！");
    }
}

    // 对 handleAdminMenuChoice 方法做同样处理
// 修改 handleAdminMenuChoice 方法，添加对标签管理的处理
private void handleAdminMenuChoice(int choice) {
    // 检查会话是否过期
//    if (userService.isSessionExpired(currentUser.getUserId())) {
//        System.out.println("会话已过期，请重新登录！");
//        logout();
//        return;
//    }
//
//    // 刷新会话时间
//    userService.refreshSession(currentUser.getUserId());

    switch (choice) {
        case 1:
            browseProducts();
            break;
        case 2:
            addToCart();
            break;
        case 3:
            viewCart();
            break;
        case 4:
            showSortedProducts();
            break;
        case 5:
            // 结算购买功能：先创建订单，再支付订单
            createOrderFromCart();    // 创建新订单
            payPendingOrders();       // 支付待支付订单
            break;
        case 6:
            searchProducts();
            break;
        case 7:  // 修改商品信息功能
            modifyProductInfo();
            break;
        case 8:  // 订单管理
            manageOrders();
            break;
        case 9:  // 商品分类管理
            manageCategories();
            break;
        case 10:
            browseProductsByCategory();
            break;
        case 11: // 用户管理
            manageUsers();
            break;
        case 12:
            manageUserInfo();
            break;
        case 13:
            manageAllPendingOrders();
            break;
        case 14: // 商品标签管理
            manageProductTags();
            break;
        case 15: // 数据统计与报表
            manageReports();
            break;
        case 16: // 退出登录选项
            manageAllOrders();
            break;
        case 17: // 订单有效期管理
            manageOrderExpiration();
            break;
        case 18:
                exitApplication();
                break;
        case 0:
            logout();
            break;
        default:
            System.out.println("无效的选项，请重新输入！");
    }
}


    private void viewAllUsers() {
        System.out.println("\n--- 所有用户 ---");
        List<User> users = getAllUsersViaNetwork();
        if (users.isEmpty()) {
            System.out.println("暂无用户。");
            return;
        }

        for (User user : users) {
            System.out.println(user.toString());
        }
    }

    private void deleteUser() {
        System.out.print("请输入要删除的用户ID: ");
        String userId = scanner.nextLine();

        if (userId.equals(currentUser.getUserId())) {
            System.out.println("不能删除当前登录用户！");
            return;
        }

        if (userId.equals("admin")) {
            System.out.println("不能删除管理员账户！");
            return;
        }

        boolean success = deleteUserViaNetwork(userId);
        if (success) {
            System.out.println("用户删除成功！");
        } else {
            System.out.println("用户删除失败！用户不存在或无权限。");
        }
    }
// 在 ConsoleShop 类中添加以下方法

    // 修改 viewMyOrders 方法，使用当前用户ID
/**
 * 查看我的订单（使用网络获取实时数据）
 */
private void viewMyOrders() {
    System.out.println("\n--- 我的订单 ---");
    List<Order> orders = getOrdersByUserViaNetwork(currentUser.getUserId());

    if (orders.isEmpty()) {
        System.out.println("您还没有订单。");
        return;
    }

    // 按创建时间倒序排列
    orders.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));

    for (Order order : orders) {
        System.out.println(order.toString());
        
        // 如果是待付款订单，显示有效期信息
        if (order.getStatus() == Order.OrderStatus.PENDING_PAYMENT) {
            String expirationInfo = checkOrderExpiredViaNetwork(order.getOrderId());
            System.out.printf("  %s%n", expirationInfo);
        }
    }
}

    /**
     * 订单有效期管理
     */
    private void manageOrderExpiration() {
        while (true) {
            System.out.println("\n--- 订单有效期管理 ---");
            System.out.println("1. 检查订单有效期");
            System.out.println("2. 手动清理过期订单");
            System.out.println("3. 查看即将过期的订单");
            System.out.println("4. 查看所有待付款订单");
            System.out.println("0. 返回上级菜单");
            System.out.print("请输入您的选择: ");

            int choice = readIntInput();

            switch (choice) {
                case 1:
                    checkOrderExpiration();
                    break;
                case 2:
                    cleanupExpiredOrders();
                    break;
                case 3:
                    viewOrdersAboutToExpire();
                    break;
                case 4:
                    viewAllPendingOrders();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效的选项！");
            }

            // 等待用户按键后继续
            System.out.println("\n按回车键继续...");
            scanner.nextLine();
        }
    }

    /**
     * 检查订单有效期
     */
    private void checkOrderExpiration() {
        System.out.print("请输入要检查的订单ID: ");
        String orderId = scanner.nextLine().trim();

        if (orderId.isEmpty()) {
            System.out.println("订单ID不能为空！");
            return;
        }

        String result = checkOrderExpiredViaNetwork(orderId);
        System.out.printf("检查结果: %s%n", result);
    }

    /**
     * 手动清理过期订单
     */
    private void cleanupExpiredOrders() {
        System.out.print("确认要清理所有过期订单吗？(y/n): ");
        String confirm = scanner.nextLine().trim();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            String result = cleanupExpiredOrdersViaNetwork();
            System.out.printf("清理结果: %s%n", result);
        } else {
            System.out.println("已取消清理操作。");
        }
    }

    /**
     * 查看即将过期的订单
     */
    private void viewOrdersAboutToExpire() {
        System.out.println("\n--- 即将过期的订单（5分钟内） ---");
        List<Order> aboutToExpire = getOrdersAboutToExpireViaNetwork();

        if (aboutToExpire.isEmpty()) {
            System.out.println("暂无即将过期的订单。");
            return;
        }

        for (Order order : aboutToExpire) {
            String remainingTime = checkOrderExpiredViaNetwork(order.getOrderId());
            System.out.printf("订单ID: %s | 用户: %s | 金额: ¥%.2f | %s%n",
                order.getOrderId(), order.getUserId(), order.getTotalPrice(), remainingTime);
        }
    }

    /**
     * 查看所有待付款订单
     */
    private void viewAllPendingOrders() {
        System.out.println("\n--- 所有待付款订单 ---");
        List<Order> allOrders = getAllOrdersViaNetwork();
        List<Order> pendingOrders = allOrders.stream()
            .filter(order -> order.getStatus() == Order.OrderStatus.PENDING_PAYMENT)
            .collect(java.util.stream.Collectors.toList());

        if (pendingOrders.isEmpty()) {
            System.out.println("暂无待付款订单。");
            return;
        }

        // 按创建时间排序
        pendingOrders.sort(Comparator.comparing(Order::getCreateTime));

        System.out.printf("订单数量: %d%n", pendingOrders.size());
        System.out.println("----------------------------------------");
        for (Order order : pendingOrders) {
            String expirationInfo = checkOrderExpiredViaNetwork(order.getOrderId());
            System.out.printf("订单ID: %s | 用户: %s | 金额: ¥%.2f | 创建时间: %s%n",
                order.getOrderId(), order.getUserId(), order.getTotalPrice(), order.getCreateTime());
            System.out.printf("  状态: %s%n", expirationInfo);
            System.out.println("----------------------------------------");
        }
    }


    /**
 * 修改 addToCart 方法，避免自动合并相同ID的商品
 * 每次添加都作为独立条目处理
 * 添加购物车数据持久化
 */
    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }

        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = readIntInput();

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }

        // 计算购物车中该商品的总数量
        int currentTotalQuantity = 0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            // 从键中提取商品ID部分进行比较
            String cartProductId = entry.getKey().split("_")[0];
            if (cartProductId.equals(productId)) {
                currentTotalQuantity += entry.getValue();
            }
        }

        // 检查是否会超过库存
        if (currentTotalQuantity + quantity > product.getStock()) {
            System.out.printf("错误：购物车中该商品总数量将超过库存限制！该商品库存为 %d，购物车中已有 %d 件，您最多还能添加 %d 件%n",
                    product.getStock(), currentTotalQuantity, product.getStock() - currentTotalQuantity);
            return;
        }

        // 为每个商品添加生成唯一的键，避免自动合并相同ID的商品
        String uniqueKey = "%s_%d".formatted(productId, System.currentTimeMillis());
        shoppingCart.put(uniqueKey, quantity);

        // 记录添加时的价格
        productPriceAtAddTime.put(uniqueKey, product.getPrice());

        // 保存购物车数据
        saveCartToFile();

        System.out.printf("成功将 '%s' 添加到购物车！数量: %d%n", product.getName(), quantity);

        // 询问是否同时添加到收藏夹
        System.out.print("是否同时添加到收藏夹？(y/n): ");
        String addToFavorites = scanner.nextLine();
        if ("y".equalsIgnoreCase(addToFavorites)) {
            userFavorites.computeIfAbsent(currentUser.getUserId(), _ -> new HashSet<>())
                    .add(productId);
            saveFavoritesToFile();
            System.out.println("商品已添加到收藏夹！");
        }
    }




    // 修改 checkout 方法，使用当前用户ID
 /*
  修改 checkout 方法，避免重复创建订单
  使用当前用户ID
 */
/*
  修改 checkout 方法，避免重复创建订单，并在第二次选择时直接进入支付流程
  使用当前用户ID
 */
/*
  结算购买 - 创建新订单
  为购物车中尚未创建订单的商品创建待支付订单
 */
/*
  结算购买 - 创建新订单
  为购物车中尚未创建订单的商品创建待支付订单
 */
/*
  结算购买 - 创建新订单
  为购物车中尚未创建订单的商品创建待支付订单
  修改为基于商品ID和数量的精确匹配判断重复订单
 */
/*
  结算购买 - 创建新订单
  为购物车中尚未创建订单的商品创建待支付订单
  修改为基于商品ID和数量的精确匹配判断重复订单
  修复购物车键解析问题
 */
// 修改 createOrderFromCart 方法中的积分处理部分

/**
 * 结算购买 - 创建新订单（优化版）
 * 支持用户选择购物车中的特定商品创建订单
 * 为购物车中尚未创建订单的商品创建待支付订单
 * 修改为基于商品ID和数量的精确匹配判断重复订单
 * 修复购物车键解析问题
 * 添加购物车数据持久化
 */
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private void createOrderFromCart() {
    if (shoppingCart.isEmpty()) {
        System.out.println("购物车是空的，请先添加商品！");
        return;
    }

    try {
        // 获取系统中所有待支付订单（不仅仅是当前用户的）
        List<Order> allPendingOrders = orderService.getOrdersByStatus(Order.OrderStatus.PENDING_PAYMENT);

        // 创建一个映射来存储待支付订单中的商品及其数量
        Map<String, Integer> pendingOrderItems = new HashMap<>();

        // 收集所有待支付订单中的商品ID和数量
        for (Order order : allPendingOrders) {
            for (Map.Entry<String, Integer> entry : order.getItems().entrySet()) {
                String productId = entry.getKey();
                Integer quantity = entry.getValue();
                // 用商品ID+数量作为键来标识完全相同的订单项
                pendingOrderItems.put("%s:%d".formatted(productId, quantity), quantity);
            }
        }

        // 显示购物车内容并标记已存在订单的商品
        System.out.println("\n--- 贸物车商品列表 ---");
        System.out.println("编号 | 选择 | 商品ID | 商品名称             | 单价     | 购买数量 | 小计     | 状态");
        System.out.println("--------------------------------------------------------------------------------");

        List<Map.Entry<String, Integer>> cartItems = new ArrayList<>(shoppingCart.entrySet());
        Map<Integer, Map.Entry<String, Integer>> selectableItems = new HashMap<>();
        int displayIndex = 1;

        for (Map.Entry<String, Integer> entry : cartItems) {
            String cartKey = entry.getKey();
            String productId = cartKey.split("_")[0]; // 提取商品ID部分
            Integer quantity = entry.getValue();

            Product product = productService.findProductById(productId);
            if (product == null) continue;

            // 检查是否已存在相同商品和数量的待支付订单
            String orderItemKey = "%s:%d".formatted(productId, quantity);
            boolean hasPendingOrder = pendingOrderItems.containsKey(orderItemKey);

            String status = hasPendingOrder ? "[已创建订单]" : "[待创建订单]";
            double itemTotal = productPriceAtAddTime.getOrDefault(cartKey, product.getPrice()) * quantity;

            System.out.printf("%-4d | %-4s | %-6s | %-20s | ¥%-7.2f | %-8d | ¥%-7.2f | %s%n",
                    displayIndex,
                    hasPendingOrder ? "×" : "√",
                    productId,
                    product.getName(),
                    productPriceAtAddTime.getOrDefault(cartKey, product.getPrice()),
                    quantity,
                    itemTotal,
                    status);

            if (!hasPendingOrder) {
                selectableItems.put(displayIndex, entry);
            }
            displayIndex++;
        }

        if (selectableItems.isEmpty()) {
            System.out.println("购物车中所有商品都已创建订单，请前往支付功能完成支付。");
            return;
        }

        System.out.println("--------------------------------------------------------------------------------");
        System.out.println("提示：输入编号选择商品，多个编号用逗号分隔，输入all选择所有商品");
        System.out.print("请选择要创建订单的商品: ");
        String selection = scanner.nextLine().trim();

        Set<Map.Entry<String, Integer>> selectedItems = new HashSet<>();
        if ("all".equalsIgnoreCase(selection)) {
            selectedItems.addAll(selectableItems.values());
        } else {
            String[] indices = selection.split(",");
            for (String indexStr : indices) {
                try {
                    int index = Integer.parseInt(indexStr.trim());
                    Map.Entry<String, Integer> item = selectableItems.get(index);
                    if (item != null) {
                        selectedItems.add(item);
                    } else {
                        System.out.printf("警告：无效的编号 %d，已忽略%n", index);
                    }
                } catch (NumberFormatException e) {
                    System.out.printf("警告：无效的输入 '%s'，已忽略%n", indexStr.trim());
                }
            }
        }

        if (selectedItems.isEmpty()) {
            System.out.println("未选择任何商品，取消创建订单操作。");
            return;
        }

        // 验证选中商品的库存是否足够
        boolean hasEnoughStock = true;
        for (Map.Entry<String, Integer> selectedItem : selectedItems) {
            String cartKey = selectedItem.getKey();
            String productId = cartKey.split("_")[0]; // 提取商品ID部分
            Integer quantity = selectedItem.getValue();

            // 使用 ProductService 中的 hasEnoughStock 方法检查库存
            if (!productService.hasEnoughStock(productId, quantity)) {
                Product product = productService.findProductById(productId);
                if (product != null) {
                    System.out.printf("错误：商品 '%s' 库存不足，当前库存：%d，需要：%d%n",
                        product.getName(), product.getStock(), quantity);
                }
                hasEnoughStock = false;
            }
        }

        if (!hasEnoughStock) {
            System.out.println("部分商品库存不足，无法创建订单。");
            return;
        }

        // 构建订单商品映射
        Map<String, Integer> orderItems = new HashMap<>();
        Set<String> keysToRemove = new HashSet<>();

        // 构建订单项
        for (Map.Entry<String, Integer> selectedItem : selectedItems) {
            String cartKey = selectedItem.getKey();
            String productId = cartKey.split("_")[0]; // 提取商品ID部分
            Integer quantity = selectedItem.getValue();

            orderItems.put(productId, quantity);
            keysToRemove.add(cartKey);
        }

        // 创建订单（通过网络连接到服务器）
        Order order = createOrderViaNetwork(currentUser.getUserId(), orderItems);

        // 从购物车中移除已购买的商品
        for (String key : keysToRemove) {
            shoppingCart.remove(key);
            productPriceAtAddTime.remove(key);
        }

        // 保存购物车数据
        saveCartToFile();

        System.out.println("订单创建成功！");
        System.out.printf("订单信息: %s%n", order);

        // 询问是否立即支付
        System.out.print("是否立即支付此订单？(y/n): ");
        String payChoice = scanner.nextLine().trim();

        if ("y".equalsIgnoreCase(payChoice) || "yes".equalsIgnoreCase(payChoice)) {
            paySingleOrder(order);
        } else {
            System.out.println("您可以稍后在订单管理中支付此订单。");
        }
    } catch (Exception e) {
        System.out.printf("创建订单失败: %s%n", e.getMessage());
    }
}

/**
 * 通过网络连接到服务器创建订单
 * @param userId 用户ID
 * @param orderItems 订单商品映射
 * @return 创建的订单对象
 * @throws RuntimeException 如果创建失败
 */
private Order createOrderViaNetwork(String userId, Map<String, Integer> orderItems) {
    Socket socket = null;
    try {
        // 创建Socket连接到服务器
        socket = new Socket(SERVER_HOST, SERVER_PORT);

        // 获取输入输出流
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 构建请求字符串
        StringBuilder requestBuilder = new StringBuilder("CREATE ORDER:");
        requestBuilder.append(userId).append(":");

        boolean first = true;
        for (Map.Entry<String, Integer> entry : orderItems.entrySet()) {
            if (!first) {
                requestBuilder.append(";");
            }
            requestBuilder.append(entry.getKey()).append(",").append(entry.getValue());
            first = false;
        }

        // 向服务器发送请求
        output.writeObject(requestBuilder.toString());
        output.flush();

        // 从服务器读取响应
        Object response = input.readObject();

        if (response instanceof Order) {
            return (Order) response;
        } else if (response instanceof String) {
            throw new RuntimeException((String) response);
        } else {
            throw new RuntimeException("服务器返回了意外的响应类型");
        }
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException("网络连接错误: %s".formatted(e.getMessage()), e);
    } finally {
        // 确保Socket被关闭
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭网络连接时出错: %s%n", e.getMessage());
            }
        }
    }
}

/**
 * 支付单个订单
 * @param order 要支付的订单
 */
private void paySingleOrder(Order order) {
    try {
        System.out.printf("订单 %s 需要支付金额: ¥%.2f%n", order.getOrderId(), order.getTotalPrice());
        System.out.print("确认支付？(y/n): ");
        String confirm = scanner.nextLine().trim();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            // 更新订单状态为已付款
            Order updatedOrder = updateOrderStatusViaNetwork(order.getOrderId(), Order.OrderStatus.PAID);
            if (updatedOrder != null) {
                System.out.println("✅ 支付成功！");
                System.out.printf("订单状态已更新为: %s%n", updatedOrder.getStatus());

                // 增加用户积分（按消费：积分=10：1的比例）
                if (currentUser != null) {
                    double pointsToAdd = order.getTotalPrice() / 10.0; // 消费10元增加1积分
                    User updatedUser = addPointsViaNetwork(currentUser.getUserId(), pointsToAdd);
                    if (updatedUser != null) {
                        System.out.printf("🎉 恭喜获得 %.1f 积分！当前总积分: %d%n", 
                            pointsToAdd, updatedUser.getPoints());
                        
                        // 检查是否自动升级为VIP
                        // 更新当前用户信息
                        if (updatedUser.getRole() == User.UserRole.VIP &&
                            currentUser.getRole() == User.UserRole.CUSTOMER) {
                            System.out.println("🌟 恭喜您自动升级为VIP用户！");
                        }
                        currentUser = updatedUser; // 更新当前用户信息
                    }
                }
            } else {
                System.out.println("❌ 支付失败，请查看上方错误信息");
            }
        } else {
            System.out.println("支付已取消");
        }
    } catch (Exception e) {
        System.out.printf("支付过程中发生错误: %s%n", e.getMessage());
    }
}

/**
 * 通过网络更新订单状态
 * @param orderId 订单ID
 * @param status 新状态
 * @return 更新后的订单对象，如果失败返回null
 */
private Order updateOrderStatusViaNetwork(String orderId, Order.OrderStatus status) {
    Socket socket = null;
    try {
        // 创建Socket连接到服务器
        socket = new Socket(SERVER_HOST, SERVER_PORT);

        // 获取输入输出流
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 构建请求字符串
        String request = String.format("UPDATE ORDER STATUS:%s:%s", orderId, status.name());

        // 向服务器发送请求
        output.writeObject(request);
        output.flush();

        // 从服务器读取响应
        Object response = input.readObject();

        if (response instanceof Order) {
            return (Order) response;
        } else if (response instanceof String errorMsg) {
            System.out.printf("支付失败原因: %s%n", errorMsg);
            return null;
        } else {
            System.out.println("服务器返回了意外的响应类型");
            return null;
        }
    } catch (IOException | ClassNotFoundException e) {
        System.out.printf("网络连接错误: %s%n", e.getMessage());
        return null;
    } finally {
        // 确保Socket被关闭
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭网络连接时出错: %s%n", e.getMessage());
            }
        }
    }
}

/**
 * 通过网络获取用户订单
 * @param userId 用户ID
 * @return 用户订单列表
 */
private List<Order> getOrdersByUserViaNetwork(String userId) {
    Socket socket = null;
    try {
        // 创建Socket连接到服务器
        socket = new Socket(SERVER_HOST, SERVER_PORT);

        // 获取输入输出流
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 构建请求字符串
        String request = "GET ORDERS BY USER:%s".formatted(userId);

        // 向服务器发送请求
        output.writeObject(request);
        output.flush();

        // 从服务器读取响应
        Object response = input.readObject();

        if (response instanceof List) {
            @SuppressWarnings("unchecked")
            List<Order> orders = (List<Order>) response;
            return orders;
        } else {
            System.out.printf("获取订单失败: %s%n", response);
            return new ArrayList<>();
        }
    } catch (IOException | ClassNotFoundException e) {
        System.out.printf("网络连接错误: %s%n", e.getMessage());
        return new ArrayList<>();
    } finally {
        // 确保Socket被关闭
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭网络连接时出错: %s%n", e.getMessage());
            }
        }
    }
}

/**
 * 通过网络获取所有订单（管理员功能）
 * @return 订单列表
 */
private List<Order> getAllOrdersViaNetwork() {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送获取所有订单的请求
        output.writeObject("GET ALL ORDERS");
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof List) {
            @SuppressWarnings("unchecked")
            List<Order> orders = (List<Order>) response;
            return orders;
        } else if (response instanceof String) {
            System.err.printf("服务器错误: %s%n", response);
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return new ArrayList<>();
}

/**
 * 通过网络进行用户登录
 * @param username 用户名
 * @param password 密码
 * @return 登录成功的用户对象，失败返回null
 */
private User loginViaNetwork(String username, String password) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送登录请求
        String request = "USER LOGIN:%s:%s".formatted(username, password);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof User) {
            return (User) response;
        } else if (response instanceof String) {
            System.err.printf("登录失败: %s%n", response);
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return null;
}

/**
 * 通过网络进行用户注册
 * @param username 用户名
 * @param password 密码
 * @param email 邮箱
 * @return 注册成功的用户对象，失败返回null
 */
private User registerViaNetwork(String username, String password, String email) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送注册请求
        String request = "USER REGISTER:%s:%s:%s".formatted(username, password, email);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof User) {
            return (User) response;
        } else if (response instanceof String) {
            System.err.printf("注册失败: %s%n", response);
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return null;
}

/**
 * 通过网络更新用户信息
 * @param userId 用户ID
 * @param email 邮箱
 * @param phone 电话
 * @param address 地址
 * @return 更新后的用户对象，失败返回null
 */
private User updateUserInfoViaNetwork(String userId, String email, String phone, String address) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送更新用户信息请求
        String request = "UPDATE USER INFO:%s:%s:%s:%s".formatted(userId, email, phone, address);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof User) {
            return (User) response;
        } else if (response instanceof String) {
            System.err.printf("更新失败: %s%n", response);
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return null;
}

/**
 * 通过网络修改密码
 * @param userId 用户ID
 * @param oldPassword 旧密码
 * @param newPassword 新密码
 * @return 是否修改成功
 */
private boolean changePasswordViaNetwork(String userId, String oldPassword, String newPassword) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送修改密码请求
        String request = "CHANGE PASSWORD:%s:%s:%s".formatted(userId, oldPassword, newPassword);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof String message) {
            if (message.contains("成功")) {
                return true;
            } else {
                System.err.println(message);
            }
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return false;
}

/**
 * 通过网络获取所有用户（管理员功能）
 * @return 用户列表
 */
private List<User> getAllUsersViaNetwork() {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送获取所有用户的请求
        output.writeObject("GET ALL USERS");
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof List) {
            @SuppressWarnings("unchecked")
            List<User> users = (List<User>) response;
            return users;
        } else if (response instanceof String) {
            System.err.printf("服务器错误: %s%n", response);
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return new ArrayList<>();
}

/**
 * 通过网络删除用户（管理员功能）
 * @param userId 用户ID
 * @return 是否删除成功
 */
private boolean deleteUserViaNetwork(String userId) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送删除用户的请求
        String request = "DELETE USER:%s".formatted(userId);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof String message) {
            if (message.contains("成功")) {
                return true;
            } else {
                System.err.println(message);
            }
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return false;
}

/**
 * 通过网络更新用户角色（管理员功能）
 * @param userId 用户ID
 * @param role 新角色
 * @return 是否更新成功
 */
private boolean updateUserRoleViaNetwork(String userId, User.UserRole role) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送更新用户角色的请求
        String request = "UPDATE USER ROLE:%s:%s".formatted(userId, role.name());
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof String message) {
            if (message.contains("成功")) {
                return true;
            } else {
                System.err.println(message);
            }
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return false;
}

/**
 * 通过网络更新用户积分（管理员功能）
 * @param userId 用户ID
 * @param points 积分变化值
 * @return 更新后的用户对象，失败返回null
 */
private User updateUserPointsViaNetwork(String userId, int points) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送更新用户积分的请求
        String request = "UPDATE USER POINTS:%s:%d".formatted(userId, points);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof User) {
            return (User) response;
        } else if (response instanceof String) {
            System.err.printf("更新失败: %s%n", response);
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return null;
}

/**
 * 通过网络查找用户
 * @param userId 用户ID
 * @return 用户对象，未找到返回null
 */
private User findUserByIdViaNetwork(String userId) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送查找用户的请求
        String request = "FIND USER BY ID:%s".formatted(userId);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof User) {
            return (User) response;
        } else if (response instanceof String) {
            System.err.printf("查找失败: %s%n", response);
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return null;
}

/**
 * 通过网络解锁用户账户（管理员功能）
 * @param userId 用户ID
 * @return 是否解锁成功
 */
private boolean unlockUserViaNetwork(String userId) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送解锁用户账户的请求
        String request = "UNLOCK USER:%s".formatted(userId);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof String message) {
            if (message.contains("成功")) {
                return true;
            } else {
                System.err.println(message);
            }
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return false;
}

    /**
 * 通过网络增加用户积分
 * @param userId 用户ID
 * @param amount 消费金额
 * @return 更新后的用户对象，失败返回null
 */
private User addPointsViaNetwork(String userId, double amount) {
    Socket socket = null;
    try {
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 发送增加积分的请求
        String request = "ADD POINTS:%s:%s".formatted(userId, amount);
        output.writeObject(request);
        output.flush();

        // 读取响应
        Object response = input.readObject();
        if (response instanceof User) {
            return (User) response;
        } else if (response instanceof String) {
            System.err.printf("增加积分失败: %s%n", response);
        }
    } catch (IOException | ClassNotFoundException e) {
        System.err.printf("网络错误: %s%n", e.getMessage());
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.printf("关闭连接时出错: %s%n", e.getMessage());
            }
        }
    }
    return null;
}

/*
  支付订单功能
  处理所有待支付订单的支付流程
 */
/*
  支付订单功能
  处理所有待支付订单的支付流程
 */
/*
  支付订单功能
  处理所有待支付订单的支付流程
 */
/*
  支付订单功能
  处理所有待支付订单的支付流程
 */
// 修改 payPendingOrders 方法，更新积分计算和VIP升级逻辑
/*
  支付订单功能
  处理所有待支付订单的支付流程
 */
// 修改 payPendingOrders 方法，修复积分更新和VIP升级逻辑

/**
 * 支付功能优化 - 支持选择一个或多个待支付订单进行支付
 * 显示所有待支付订单，允许用户选择要支付的订单
 */
private void payPendingOrders() {
    // 获取当前用户的所有待支付订单（通过网络）
    List<Order> pendingOrders = getOrdersByUserViaNetwork(currentUser.getUserId());
    
    // 过滤出待支付订单
    pendingOrders = pendingOrders.stream()
        .filter(order -> order.getStatus() == Order.OrderStatus.PENDING_PAYMENT)
        .toList();

    if (pendingOrders.isEmpty()) {
        System.out.println("您没有待支付的订单。");
        return;
    }

    // 显示所有待支付订单
    System.out.println("\n--- 待支付订单列表 ---");
    System.out.println("订单ID\t\t| 商品信息\t\t\t| 总价\t\t| 创建时间");
    System.out.println("--------------------------------------------------------------------------");

    for (int i = 0; i < pendingOrders.size(); i++) {
        Order order = pendingOrders.get(i);
        System.out.printf("%d. %s\t| %d种商品\t\t\t| ¥%.2f\t| %s%n",
            i + 1,
            order.getOrderId(),
            order.getItems().size(),
            order.getTotalPrice(),
            order.getCreateTime().toLocalDate());
    }

    // 让用户选择要支付的订单
    System.out.println("\n请选择要支付的订单:");
    System.out.println("1. 支付所有订单");
    System.out.println("2. 选择特定订单支付");
    System.out.print("请输入您的选择 (1-2): ");

    int choice = readIntInput();
    List<Order> ordersToPay = new ArrayList<>();

    if (choice == 1) {
        // 支付所有订单
        ordersToPay.addAll(pendingOrders);
    } else if (choice == 2) {
        // 选择特定订单支付
        System.out.println("请输入要支付的订单编号(多个编号用逗号分隔，如: 1,3,5):");
        String input = scanner.nextLine().trim();

        try {
            String[] indices = input.split(",");
            for (String indexStr : indices) {
                int index = Integer.parseInt(indexStr.trim());
                if (index >= 1 && index <= pendingOrders.size()) {
                    ordersToPay.add(pendingOrders.get(index - 1));
                } else {
                    System.out.printf("无效的订单编号: %d%n", index);
                }
            }
        } catch (NumberFormatException e) {
            System.out.println("输入格式错误，请输入有效的订单编号。");
            return;
        }
    } else {
        System.out.println("无效的选择。");
        return;
    }

    if (ordersToPay.isEmpty()) {
        System.out.println("未选择任何订单进行支付。");
        return;
    }

    // 计算总金额
    double totalAmount = ordersToPay.stream()
        .mapToDouble(Order::getTotalPrice)
        .sum();

    // 显示待支付订单详情
    System.out.println("\n--- 确认支付信息 ---");
    System.out.println("将支付以下订单:");
    for (Order order : ordersToPay) {
        System.out.printf("- 订单 %s: ¥%.2f%n", order.getOrderId(), order.getTotalPrice());
    }
    System.out.printf("总金额: ¥%.2f%n", totalAmount);

    // 确认支付
    System.out.print("确认支付吗？(y/n): ");
    String confirm = scanner.nextLine();

    if (!"y".equalsIgnoreCase(confirm)) {
        System.out.println("支付已取消。");
        return;
    }

    // 执行支付
    boolean allSuccess = true;
    for (Order order : ordersToPay) {
        Order updatedOrder = updateOrderStatusViaNetwork(order.getOrderId(), Order.OrderStatus.PAID);
        if (updatedOrder != null) {
            System.out.printf("订单 %s 支付成功！%n", order.getOrderId());

            // 增加用户积分（按消费：积分=10：1的比例）
            if (currentUser != null) {
                double pointsToAdd = order.getTotalPrice() / 10.0; // 消费10元增加1积分
                User updatedUser = addPointsViaNetwork(currentUser.getUserId(), pointsToAdd*10);
                if (updatedUser != null) {
                      System.out.printf("🎉 恭喜获得 %.1f 积分！当前总积分: %d%n",
       pointsToAdd, updatedUser.getPoints());

                    
                    // 检查是否自动升级为VIP
                    // 更新当前用户信息
                    if (updatedUser.getRole() == User.UserRole.VIP &&
                        currentUser.getRole() == User.UserRole.CUSTOMER) {
                        System.out.println("🌟 恭喜您自动升级为VIP用户！");
                    }
                    currentUser = updatedUser; // 更新当前用户信息
                }
            }

            // 从购物车中移除已购买的商品
            for (String productId : order.getItems().keySet()) {
                shoppingCart.remove(productId);
            }
        } else {
            System.out.printf("订单 %s 支付失败！%n", order.getOrderId());
            allSuccess = false;
        }
    }

    if (allSuccess) {
        // 根据消费金额为用户增加积分 (按10:1比例)
        int earnedPoints = (int) (totalAmount / 10); // 每消费10元获得1积分
        int originalPoints = currentUser.getPoints(); // 记录原始积分

        // 通过网络增加用户积分
        User updatedUser = addPointsViaNetwork(currentUser.getUserId(), totalAmount);
        if (updatedUser != null) {
            System.out.printf("本次消费 ¥%.2f，获得 %d 积分！%n", totalAmount, earnedPoints);
            System.out.printf("积分变动: %d -> %d (+%d)%n", originalPoints, updatedUser.getPoints(), earnedPoints);

            // 更新当前用户信息以反映最新的积分
            currentUser = updatedUser;

            // 检查是否达到VIP条件（积分达到1000分）
            if (currentUser.getRole() != User.UserRole.VIP && currentUser.getPoints() >= 1000) {
                System.out.println("恭喜您！积分已达到1000分，已自动升级为VIP用户！");
                System.out.printf("用户角色已更新为: %s%n", currentUser.getRole());
            }
        } else {
            System.out.println("积分更新失败！");
        }

        System.out.println("支付完成！");

        // 只有管理员可以设置订单为配送状态
        if (currentUser.getRole() == User.UserRole.ADMIN) {
            // 询问用户是否立即将订单设为配送中状态
            System.out.print("是否立即将所有已支付订单设为配送中状态？(y/n): ");
            String shipConfirm = scanner.nextLine();

            if ("y".equalsIgnoreCase(shipConfirm)) {
                // 将已支付订单更新为配送中状态
                for (Order order : ordersToPay) {
                    orderService.updateOrderStatus(order.getOrderId(), Order.OrderStatus.SHIPPING);
                    System.out.printf("订单 %s 已切换到配送中状态！%n", order.getOrderId());
                }
                System.out.println("所有订单已进入配送流程，感谢您的购买！");
            } else {
                System.out.println("订单已支付但尚未配送，请前往订单管理手动设置配送状态。");
            }
        } else {
            System.out.println("订单已支付，等待管理员设置配送状态。");
        }
    } else {
        System.out.println("部分订单支付失败，请检查订单状态。");
    }
}





    // 改进 readIntInput 方法
    private int readIntInput() {
        try {
            int input = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符
            return input;
        } catch (Exception e) {
            scanner.nextLine(); // 清除非法输入
            System.out.print("输入格式错误，请输入数字: ");
            return readIntInput(); // 递归重试
        }
    }

    private double readDoubleInput() {
        try {
            double input = scanner.nextDouble();
            scanner.nextLine();
            return input;
        } catch (Exception e) {
            scanner.nextLine();
            System.out.print("输入格式错误，请重新输入: ");
            return readDoubleInput();
        }
    }

    // 其他原有方法保持不变...
    private void showSortedProducts() {
        System.out.println("\n--- 请选择排序方式 ---");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少.");
        System.out.print("请输入您的选择: ");

        int sortChoice = readIntInput();

        switch (sortChoice) {
            case 1:
                browseProducts(ProductSorters.BY_PRICE_ASC);
                break;
            case 2:
                browseProducts(ProductSorters.BY_PRICE_DESC);
                break;
            case 3:
                browseProducts(ProductSorters.BY_STOCK_DESC);
                break;
            default:
                System.out.println("无效的排序选项！");
        }
    }

    private void browseProducts(Comparator<Product> comparator) {
        if (currentUser == null) {
            System.out.println("请先登录");
            return;
        }

        Socket socket = null;
        try {
            // 创建Socket连接到服务器
            socket = new Socket(SERVER_HOST, SERVER_PORT);

            // 获取输入输出流
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 向服务器发送请求
            output.writeObject("GET ALL PRODUCTS");
            output.flush();

            // 从服务器读取响应
            Object response = input.readObject();

            if (response instanceof List) {
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) response;

                System.out.println("\n--- 商品列表 ---");
                if (products.isEmpty()) {
                    System.out.println("商店里还没有商品。");
                } else {
                    // 应用排序（如果指定了比较器）
                    if (comparator != null) {
                        products.sort(comparator);
                    } else {
                        Collections.sort(products);
                    }

                    for (Product product : products) {
                        System.out.println(product.toString());
                    }
                }
            } else {
                System.out.printf("获取商品列表失败: %s%n", response);
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.printf("浏览商品时发生错误: %s%n", e.getMessage());
        } finally {
            // 确保Socket被关闭
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭Socket时发生错误: %s%n", e.getMessage());
                }
            }
        }
    }
    private void browseProducts() {
        browseProducts(null);
    }
    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        System.out.println("商品ID | 商品名称             | 原价     | 现价     | 购买数量 | 小计     | 库存 ");
        System.out.println("--------------------------------------------------------------------------------");
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String cartKey = entry.getKey();
            // 从购物车键中提取实际的商品ID
            String productId = cartKey.contains("_") ? cartKey.split("_")[0] : cartKey;
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                // 获取添加时的价格
                Double originalPrice = productPriceAtAddTime.get(cartKey);
                double currentPrice = product.getPrice();

                // 检查价格变动
                String priceChangeIndicator;
                if (originalPrice != null && originalPrice != currentPrice) {
                    priceChangeIndicator = originalPrice > currentPrice ? "(降价)" : "(涨价)";
                    System.out.printf("提醒: 商品 '%s' 价格已变动 %s%n", product.getName(), priceChangeIndicator);
                }

                // 实时库存检查
                if (quantity > product.getStock()) {
                    System.out.printf("警告: 商品 '%s' 的购买数量(%d)已超过当前库存(%d)，请修改数量或移除该商品%n",
                            product.getName(), quantity, product.getStock());
                }

                double subtotal = currentPrice * quantity;
                System.out.printf("%-6s | %-20s | %-8s | ¥%-7.2f | %-8d | ¥%-7.2f | %-4d\n",
                        product.getId(),
                        product.getName(),
                        originalPrice != null ? String.format("¥%.2f", originalPrice) : "N/A",
                        currentPrice,
                        quantity,
                        subtotal,
                        product.getStock());
                total += subtotal;
            } else {
                System.out.printf("警告: 商品 %s 已下架或不存在%n", productId);
            }
        }
        System.out.println("--------------------------------------------------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);

        // 提醒用户检查库存状态
        checkCartStockStatus();
    }

/**
 * 检查购物车中商品的库存状态
 */
private void checkCartStockStatus() {
    boolean hasStockIssue = false;
    for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
        String cartKey = entry.getKey();
        String productId = cartKey.contains("_") ? cartKey.split("_")[0] : cartKey;
        Integer quantity = entry.getValue();
        Product product = productService.findProductById(productId);
        if (product != null && quantity > product.getStock()) {
            hasStockIssue = true;
            break;
        }
    }

    if (hasStockIssue) {
        System.out.println("提示: 购物车中存在库存不足的商品，请及时处理！");
    }
}
// 在 ConsoleShop 类中添加用户收藏列表
private final Map<String, Set<String>> userFavorites = new ConcurrentHashMap<>();

    /**
 * 查看收藏夹
 */
    private void addFavoriteToCart() {
        Set<String> favorites = userFavorites.get(currentUser.getUserId());

        if (favorites == null || favorites.isEmpty()) {
            System.out.println("您的收藏夹是空的！");
            return;
        }

        System.out.print("请输入要添加到购物车的商品ID: ");
        String productId = scanner.nextLine();

        if (favorites.contains(productId)) {
            Product product = productService.findProductById(productId);
            if (product != null) {
                System.out.printf("商品 '%s' 当前库存: %d%n", product.getName(), product.getStock());
                System.out.print("请输入购买数量: ");
                int quantity = readIntInput();

                if (quantity <= 0) {
                    System.out.println("错误：购买数量必须为正数！");
                    return;
                }

                if (quantity > product.getStock()) {
                    System.out.println("错误：购买数量超过库存！");
                    return;
                }

                // 添加到购物车
                String uniqueKey = "%s_%d".formatted(productId, System.currentTimeMillis());
                shoppingCart.put(uniqueKey, quantity);
                productPriceAtAddTime.put(uniqueKey, product.getPrice());

                System.out.printf("成功将 '%s' 添加到购物车！数量: %d%n", product.getName(), quantity);
            } else {
                System.out.println("商品已下架！");
            }
        } else {
            System.out.println("该商品不在您的收藏夹中！");
        }
    }
    private void manageFavorites() {
        while (true) {
            System.out.println("\n--- 收藏夹管理 ---");
            System.out.println("1. 查看收藏夹");
            System.out.println("2. 添加商品到收藏夹");
            System.out.println("3. 从收藏夹移除商品");
            System.out.println("4. 从购物车移动商品到收藏夹");
            System.out.println("5. 从收藏夹添加商品到购物车");
            System.out.println("0. 返回上级菜单");
            System.out.print("请输入您的选择: ");

            int choice = readIntInput();

            switch (choice) {
                case 1:
                    viewFavorites();
                    break;
                case 2:
                    favoriteProduct();
                    break;
                case 3:
                    removeFavorite();
                    break;
                case 4:
                    moveCartToFavorite();
                    break;
                case 5:
                    addFavoriteToCart();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效的选项！");
            }
        }
    }
    private void viewFavorites() {
        Set<String> favorites = userFavorites.get(currentUser.getUserId());

        if (favorites == null || favorites.isEmpty()) {
            System.out.println("您的收藏夹是空的！");
            return;
        }

        System.out.println("\n--- 我的收藏夹 ---");
        System.out.println("商品ID | 商品名称             | 价格     | 库存 ");
        System.out.println("------------------------------------------------");

        for (String productId : favorites) {
            Product product = productService.findProductById(productId);
            if (product != null) {
                System.out.printf("%-6s | %-20s | ¥%-7.2f | %-4d\n",
                        product.getId(), product.getName(), product.getPrice(), product.getStock());
            } else {
                System.out.printf("%-6s | 商品已下架%n", productId);
            }
        }
        System.out.println("------------------------------------------------");
    }
    private void removeFavorite() {
        Set<String> favorites = userFavorites.get(currentUser.getUserId());

        if (favorites == null || favorites.isEmpty()) {
            System.out.println("您的收藏夹是空的！");
            return;
        }

        System.out.print("请输入要移除的商品ID: ");
        String productId = scanner.nextLine();

        if (favorites.remove(productId)) {
            System.out.println("商品已从收藏夹中移除！");
        } else {
            System.out.println("该商品不在您的收藏夹中！");
        }
    }
    private void moveCartToFavorite() {
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的！");
            return;
        }

        System.out.print("请输入要移至收藏夹的商品ID: ");
        String productId = scanner.nextLine();

        String cartKeyToRemove = null;
        for (String cartKey : shoppingCart.keySet()) {
            String cartProductId = cartKey.contains("_") ? cartKey.split("_")[0] : cartKey;
            if (cartProductId.equals(productId)) {
                cartKeyToRemove = cartKey;
                break;
            }
        }

        if (cartKeyToRemove != null) {
            // 从购物车移除
            shoppingCart.remove(cartKeyToRemove);
            productPriceAtAddTime.remove(cartKeyToRemove);

            // 添加到收藏夹
            Set<String> favorites = userFavorites.computeIfAbsent(currentUser.getUserId(), _ -> new HashSet<>());
            favorites.add(productId);

            Product product = productService.findProductById(productId);
            if (product != null) {
                System.out.printf("商品 '%s' 已从购物车移至收藏夹！%n", product.getName());
            }
        } else {
            System.out.println("购物车中未找到该商品！");
        }
    }
// 在 ConsoleShop 类中添加购物车持久化方法

    private void favoriteProduct() {
        System.out.print("请输入要收藏的商品ID: ");
        String productId = scanner.nextLine();

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }

        // 获取当前用户的收藏列表
        Set<String> favorites = userFavorites.computeIfAbsent(currentUser.getUserId(), _ -> new HashSet<>());

        if (favorites.add(productId)) {
            System.out.printf("商品 '%s' 已成功添加到您的收藏夹！%n", product.getName());
        } else {
            System.out.printf("商品 '%s' 已在您的收藏夹中！%n", product.getName());
        }
    }

    /**
 * 保存购物车数据到文件
 */
private void saveCartToFile() {
    if (currentUser == null) {
        return;
    }

    try {
        // 创建用户购物车数据文件
        String cartFileName = "cart_%s.dat".formatted(currentUser.getUserId());
        Map<String, Object> cartData = new HashMap<>();
        cartData.put("shoppingCart", shoppingCart);
        cartData.put("productPriceAtAddTime", productPriceAtAddTime);

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cartFileName))) {
            oos.writeObject(cartData);
        }
        System.out.println("购物车数据保存成功");
    } catch (Exception e) {
        System.err.printf("保存购物车数据时发生错误: %s%n", e.getMessage());
    }
}

/**
 * 从文件加载购物车数据
 */
private void loadCartFromFile() {
    if (currentUser == null) {
        return;
    }

    try {
        // 构造用户购物车数据文件名
        String cartFileName = "cart_%s.dat".formatted(currentUser.getUserId());
        File cartFile = new File(cartFileName);

        if (cartFile.exists()) {
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cartFileName))) {
                @SuppressWarnings("unchecked")
                Map<String, Object> cartData = (Map<String, Object>) ois.readObject();

                // 恢复购物车数据
                @SuppressWarnings("unchecked")
                Map<String, Integer> loadedCart = (Map<String, Integer>) cartData.get("shoppingCart");
                if (loadedCart != null) {
                    shoppingCart.clear();
                    shoppingCart.putAll(loadedCart);
                }

                // 恢复商品价格记录
                @SuppressWarnings("unchecked")
                Map<String, Double> loadedPrices = (Map<String, Double>) cartData.get("productPriceAtAddTime");
                if (loadedPrices != null) {
                    productPriceAtAddTime.clear();
                    productPriceAtAddTime.putAll(loadedPrices);
                }

                System.out.println("购物车数据加载成功");
            }
        } else {
            // 文件不存在，清空当前购物车数据
            shoppingCart.clear();
            productPriceAtAddTime.clear();
            System.out.println("未找到购物车数据文件，初始化空购物车");
        }
    } catch (Exception e) {
        System.out.printf("购物车数据加载失败: %s%n", e.getMessage());
        // 出错时清空购物车数据
        shoppingCart.clear();
        productPriceAtAddTime.clear();
    }
}



    // 修改 logout 方法，在退出前保存购物车数据

    /**
 * 用户退出登录
 * 保存购物车和收藏夹数据并返回到登录界面
 */
private void logout() {
    System.out.println("正在保存数据...");
    try {
        // 保存购物车数据
        if (currentUser != null) {
            saveCartToFile();
            saveFavoritesToFile();
        }
        System.out.println("数据保存完成");
    } catch (Exception e) {
        System.err.printf("保存数据时出错: %s%n", e.getMessage());
    }

    currentUser = null;
    System.out.println("已退出登录！");
    start();
}



    private void searchProducts() {
        System.out.println("\n--- 商品搜索 ---");
        System.out.println("请选择搜索方式:");
        System.out.println("1. 按商品ID搜索");
        System.out.println("2. 按商品名称搜索");
        System.out.println("3. 按价格范围搜索");
        System.out.print("请输入您的选择： ");

        int searchChoice = readIntInput();

        List<Product> results = new ArrayList<>();

        switch (searchChoice) {
            case 1:
                System.out.print("请输入商品ID: ");
                String id = scanner.nextLine();
                Product productById = productService.findProductById(id);
                if (productById != null) {
                    results.add(productById);
                }
                break;

            case 2:
                System.out.print("请输入商品名称关键字: ");
                String nameKeyword = scanner.nextLine();
                List<Product> allProducts = productService.getAllProducts();
                for (Product product : allProducts) {
                    if (product.getName().toLowerCase().contains(nameKeyword.toLowerCase())) {
                        results.add(product);
                    }
                }
                break;

            case 3:
                try {
                    System.out.print("请输入最低价格: ");
                    double minPrice = readDoubleInput();
                    System.out.print("请输入最高价格: ");
                    double maxPrice = readDoubleInput();

                    List<Product> products = productService.getAllProducts();
                    for (Product product : products) {
                        if (product.getPrice() >= minPrice && product.getPrice() <= maxPrice) {
                            results.add(product);
                        }
                    }
                } catch (Exception e) {
                    System.out.println("输入格式错误，请输入有效的数字！");
                    return;
                }
                break;

            default:
                System.out.println("无效的搜索选项！");
                return;
        }

        if (results.isEmpty()) {
            System.out.println("未找到匹配的商品。");
        } else {
            System.out.println("\n--- 搜索结果 ---");
            for (Product product : results) {
                System.out.println(product.toString());
            }
        }
    }

    // 添加修改库存的方法
    // 在 ConsoleShop.java 中添加修改商品信息的方法
    /*
      修改商品信息功能（价格、名称、ID）
     */
    /**
     * 修改商品信息功能（名称、价格、库存、ID、标签）
     */
    private void modifyProductInfo() {
        System.out.println("\n--- 修改商品信息 ---");
        System.out.print("请输入要修改的商品ID: ");
        String productId = scanner.nextLine();

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }

        System.out.println("当前商品信息:");
        System.out.println(product);

        while (true) {
            System.out.println("\n请选择要修改的信息:");
            System.out.println("1. 修改商品名称");
            System.out.println("2. 修改商品价格");
            System.out.println("3. 修改商品库存");
            System.out.println("4. 修改商品ID");
            System.out.println("5. 修改商品标签");
            System.out.println("0. 返回上级菜单");
            System.out.print("请输入您的选择: ");

            int modifyChoice = readIntInput();

            switch (modifyChoice) {
                case 1:
                    modifyProductName(product);
                    break;
                case 2:
                    modifyProductPrice(product);
                    break;
                case 3:
                    modifyProductStock(product);
                    break;
                case 4:
                    modifyProductId(product);
                    break;
                case 5:
                    modifyProductTags(product);
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效的选项！");
            }

            // 等待用户按键后继续
            System.out.println("\n按回车键继续...");
            scanner.nextLine();
        }
    }

    /**
     * 修改商品价格的方法
     * 该方法允许用户输入新的商品价格，并调用服务层更新商品信息
     *
     * @param product 商品对象，包含待修改价格的商品信息
     */
    private void modifyProductPrice(Product product) {
        // 提示用户输入新的商品价格
        System.out.print("请输入新的商品价格: ");

        try {
            // 读取用户输入的价格值
            double newPrice = readDoubleInput();

            // 验证价格是否为非负数
            if (newPrice < 0) {
                System.out.println("错误：价格不能为负数！");
                return; // 如果价格为负数，则返回并结束方法执行
            }

            // 调用服务层方法更新商品价格，传入商品ID和新价格
            Product updatedProduct = productService.updatePrice(product.getId(), newPrice);
            
            // 通过网络同步到服务器
            updateProductViaNetwork(product.getId(), "price", String.valueOf(newPrice));

            // 检查更新结果
            if (updatedProduct != null) {
                // 更新成功时，显示成功提示和更新后的商品信息
                System.out.println("成功修改商品价格!");
                System.out.println("修改后的商品信息:");
                System.out.println(updatedProduct);
            } else {
                // 更新失败时显示失败提示
                System.out.println("修改失败！");
            }
        } catch (Exception e) {
            // 处理输入格式异常，如用户输入非数字字符
            System.out.println("输入格式错误，请输入有效数字！");
        }
    }


    /**
     * 修改商品名称
     */
    private void modifyProductName(Product product) {
        System.out.print("请输入新的商品名称: ");
        String newName = scanner.nextLine();

        if (newName == null || newName.trim().isEmpty()) {
            System.out.println("错误：商品名称不能为空！");
            return;
        }

        Product updatedProduct = productService.updateName(product.getId(), newName);
        
        // 通过网络同步到服务器
        updateProductViaNetwork(product.getId(), "name", newName);

        if (updatedProduct != null) {
            System.out.println("成功修改商品名称!");
            System.out.println("修改后的商品信息:");
            System.out.println(updatedProduct);
        } else {
            System.out.println("修改失败！");
        }
    }

    /**
     * 修改商品库存
     */
    private void modifyProductStock(Product product) {
        System.out.print("请输入新的库存数量: ");

        try {
            int newStock = readIntInput();
            if (newStock < 0) {
                System.out.println("错误：库存数量不能为负数！");
                return;
            }

            Product updatedProduct = productService.updateStock(product.getId(), newStock);
            
            // 通过网络同步到服务器
            updateProductViaNetwork(product.getId(), "stock", String.valueOf(newStock));

            if (updatedProduct != null) {
                System.out.println("成功修改库存!");
                System.out.println("修改后的商品信息:");
                System.out.println(updatedProduct);
            } else {
                System.out.println("修改失败！");
            }
        } catch (Exception e) {
            System.out.println("输入格式错误，请输入有效整数！");
        }
    }

    /**
     * 通过网络更新商品信息
     * @param productId 商品ID
     * @param field 字段名
     * @param newValue 新值
     */
    private void updateProductViaNetwork(String productId, String field, String newValue) {
        Socket socket = null;
        try {
            // 创建Socket连接到服务器
            socket = new Socket(SERVER_HOST, SERVER_PORT);

            // 获取输入输出流
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 构建请求字符串
            String request = String.format("UPDATE PRODUCT:%s:%s:%s", productId, field, newValue);
            
            // 向服务器发送请求
            output.writeObject(request);
            output.flush();

            // 从服务器读取响应
            Object response = input.readObject();
            if (response instanceof String) {
                System.out.printf("服务器响应: %s%n", response);
            }
        } catch (IOException | ClassNotFoundException e) {
            System.out.printf("网络连接错误: %s%n", e.getMessage());
        } finally {
            // 确保Socket被关闭
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭网络连接时出错: %s%n", e.getMessage());
                }
            }
        }
    }

    /**
     * 修改商品标签
     */
    private void modifyProductTags(Product product) {
        System.out.printf("当前标签: %s%n", product.getTags() != null ? product.getTags().toString() : "无标签");
        System.out.println("请输入新的标签(多个标签用逗号分隔，如: 编程,技术,畅销): ");
        String tagsInput = scanner.nextLine();

        Set<String> newTags = new HashSet<>();
        if (!tagsInput.trim().isEmpty()) {
            String[] tagsArray = tagsInput.split(",");
            for (String tag : tagsArray) {
                String trimmedTag = tag.trim();
                if (!trimmedTag.isEmpty()) {
                    newTags.add(trimmedTag);
                }
            }
        }

        Product updatedProduct = productService.updateTags(product.getId(), newTags);
        if (updatedProduct != null) {
            System.out.println("成功修改商品标签!");
            System.out.println("修改后的商品信息:");
            System.out.println(updatedProduct);
        } else {
            System.out.println("修改失败！");
        }
    }

    /**
     * 修改商品ID
     */
    private void modifyProductId(Product product) {
        System.out.print("请输入新的商品ID: ");
        String newId = scanner.nextLine();

        if (newId == null || newId.trim().isEmpty()) {
            System.out.println("错误：商品ID不能为空！");
            return;
        }

        Product updatedProduct = productService.updateId(product.getId(), newId);
        if (updatedProduct != null) {
            System.out.println("成功修改商品ID!");
            System.out.println("修改后的商品信息:");
            System.out.println(updatedProduct);
        } else {
            System.out.println("修改失败！");
        }
    }

    /*
      订单管理功能
     */
    /*
      订单管理功能
     */
    /*
      订单管理功能
     */

    /**
 * 管理员订单管理功能
 */
private void manageAllOrders() {
    while (true) {
        System.out.println("\n--- 订单管理 ---");
        System.out.println("1. 查看所有订单");
        System.out.println("2. 按状态筛选订单");
        System.out.println("3. 按用户筛选订单");
        System.out.println("4. 修改订单状态");
        System.out.println("5. 查看订单详情");
        System.out.println("6. 取消订单");
        System.out.println("0. 返回上级菜单");
        System.out.print("请输入您的选择: ");

        int choice = readIntInput();

        switch (choice) {
            case 1:
                viewAllOrders();
                break;
            case 2:
                filterOrdersByStatus();
                break;
            case 3:
                filterOrdersByUser();
                break;
            case 4:
                updateOrderStatusAdmin();
                break;
            case 5:
                viewOrderDetailsAdmin();
                break;
            case 6:
                cancelOrderAdmin();
                break;
            case 0:
                return;
            default:
                System.out.println("无效选择，请重新输入！");
        }
    }
}
/**
 * Admin function: Cancel a specific order by ID
 */
private void cancelOrderAdmin() {
    System.out.print("请输入要取消的订单ID: ");
    String orderId = scanner.nextLine();

    Order order = findOrderByIdViaNetwork(orderId);
    if (order == null) {
        System.out.println("未找到该订单！");
        return;
    }

    if (order.getStatus() == Order.OrderStatus.CANCELLED) {
        System.out.println("该订单已被取消！");
        return;
    }

    Order updatedOrder = updateOrderStatusViaNetwork(orderId, Order.OrderStatus.CANCELLED);
    if (updatedOrder != null) {
        System.out.printf("订单 %s 已成功取消！%n", orderId);
    } else {
        System.out.println("订单取消失败！");
    }
}

private void manageOrders() {
    while (true) {
        System.out.println("\n--- 订单管理 ---");
        System.out.println("1. 查看所有订单");
        System.out.println("2. 按状态查看订单");
        System.out.println("3. 更新订单状态");
        System.out.println("4. 查看订单详情");
        System.out.println("5. 查看我的订单");
        System.out.println("6. 控制订单状态流转");
        System.out.println("7. 订单取消和退款");
        System.out.println("8. 订单物流跟踪");
        System.out.println("9. 订单打印/导出");
        System.out.println("10. 批量处理订单");
        System.out.println("0. 返回上级菜单");
        System.out.print("请输入您的选择: ");

        int choice = readIntInput();

        switch (choice) {
            case 1:
                if (currentUser.getRole() == User.UserRole.ADMIN) {
                    List<Order> allOrders = getAllOrdersViaNetwork();
                    if (!allOrders.isEmpty()) {
                        System.out.println("\n--- 所有订单 ---");
                        for (Order order : allOrders) {
                            System.out.println(order.toString());
                        }
                    } else {
                        System.out.println("暂无订单。");
                    }
                } else {
                    System.out.println("权限不足！");
                }
                break;
            case 2:
                filterOrdersByStatus();
                break;
            case 3:
                updateOrderStatus();
                break;
            case 4:
                if (currentUser.getRole() == User.UserRole.ADMIN) {
                    viewOrderDetailsAdmin();
                } else {
                    viewOrderDetails();
                }
                break;
            case 5:
                viewMyOrders();
                break;
            case 6:
                controlOrderStatusFlow();
                break;
            case 7:
                cancelAndRefundOrder();
                break;
            case 8:
                trackMyOrderShipping();
                break;
            case 9:
                printOrder();
                break;
            case 10:
                batchProcessOrders();
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选项！");
        }

        // 等待用户按键后继续
        System.out.println("\n按回车键继续...");
        scanner.nextLine();
    }
}

/**
 * 客户订单管理功能
 */
private void customerOrderManagement() {
    while (true) {
        System.out.println("\n--- 我的订单管理 ---");
        System.out.println("1. 查看我的所有订单");
        System.out.println("2. 按状态查看我的订单");
        System.out.println("3. 查看订单详情");
        System.out.println("4. 订单取消");
        System.out.println("5. 订单取消和退款申请");
        System.out.println("6. 订单物流跟踪");
        System.out.println("7. 打印/导出订单");
        System.out.println("0. 返回上级菜单");
        System.out.print("请输入您的选择: ");

        int choice = readIntInput();

        switch (choice) {
            case 1:
                viewMyOrders();
                break;
            case 2:
                // 按状态查看订单的实现
                System.out.println("按状态查看订单功能");
                break;
            case 3:
                // 查看订单详情的实现
                viewOrderDetails();
                break;
            case 4:
                cancelOrder();
                break;
            case 5:
                // 订单取消和退款申请的实现
                cancelAndRefundOrder();
                break;
            case 6:
                trackMyOrderShipping();
                break;
            case 7:
                // 打印/导出订单的实现
                printMyOrder();
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选项！");
        }

        // 等待用户按键后继续
        System.out.println("\n按回车键继续...");
        scanner.nextLine();
    }
}


    /**
 * 跟踪我的订单物流（使用网络获取实时数据）
 */
private void trackMyOrderShipping() {
    System.out.print("请输入订单ID: ");
    String orderId = scanner.nextLine();

    Order order = findOrderByIdViaNetwork(orderId);
    if (order == null) {
        System.out.println("未找到该订单！");
        return;
    }

    // 验证订单是否属于当前用户
    if (!order.getUserId().equals(currentUser.getUserId())) {
        System.out.println("您无权查看此订单！");
        return;
    }

    if (order.getStatus() != Order.OrderStatus.SHIPPING) {
        System.out.println("该订单尚未进入配送状态，无法跟踪物流信息。");
        return;
    }

    // 显示物流信息
    displayShippingInfo(order);
}

/**
 * 打印我的订单
 */
private void printMyOrder() {
    System.out.print("请输入订单ID: ");
    String orderId = scanner.nextLine();

    Order order = orderService.findOrderById(orderId);
    if (order == null) {
        System.out.println("未找到该订单！");
        return;
    }

    // 验证订单是否属于当前用户
    if (!order.getUserId().equals(currentUser.getUserId())) {
        System.out.println("您无权查看此订单！");
        return;
    }

    System.out.println("\n--- 订单打印选项 ---");
    System.out.println("1. 屏幕显示订单详情");
    System.out.println("2. 导出订单为文本文件");
    System.out.print("请选择操作: ");

    int choice = readIntInput();

    switch (choice) {
        case 1:
            displayOrderForPrint(order);
            break;
        case 2:
            exportOrderToFile(order);
            break;
        default:
            System.out.println("无效的选项！");
    }
}

    /**
 * 显示订单物流信息
 * @param order 订单对象
 */
private void displayShippingInfo(Order order) {
    System.out.println("\n=== 订单物流信息 ===");
    System.out.printf("订单ID: %s%n", order.getOrderId());
    System.out.printf("配送状态: %s%n", getOrderShippingStatus(order));
    System.out.printf("预计送达时间: %s%n", getEstimatedDeliveryTime(order));
    System.out.println("\n物流节点:");

    // 模拟物流节点信息
    List<String> shippingSteps = generateShippingSteps(order);
    for (int i = 0; i < shippingSteps.size(); i++) {
        System.out.printf("%d. %s%n", i + 1, shippingSteps.get(i));
    }
}
/**
 * 订单批量处理功能
 */
private void batchProcessOrders() {
    System.out.println("\n--- 批量处理订单 ---");
    System.out.println("1. 批量确认支付");
    System.out.println("2. 批量设置为配送中");
    System.out.println("3. 批量完成订单");
    System.out.print("请选择操作: ");

    int choice = readIntInput();

    switch (choice) {
        case 1:
            batchConfirmPayment();
            break;
        case 2:
            batchSetShipping();
            break;
        case 3:
            batchCompleteOrders();
            break;
        default:
            System.out.println("无效的选项！");
    }
}

/**
 * 批量确认支付
 */
private void batchConfirmPayment() {
    // 获取所有订单并筛选待支付订单（通过网络）
    List<Order> allOrders = getAllOrdersViaNetwork();
    List<Order> pendingOrders = allOrders.stream()
        .filter(order -> order.getStatus() == Order.OrderStatus.PENDING_PAYMENT)
        .toList();

    if (pendingOrders.isEmpty()) {
        System.out.println("没有待支付的订单。");
        return;
    }

    System.out.printf("找到 %d 个待支付订单:%n", pendingOrders.size());
    for (int i = 0; i < pendingOrders.size(); i++) {
        Order order = pendingOrders.get(i);
        System.out.printf("%d. 订单ID: %s, 金额: ￥%.2f, 用户: %s%n",
            i + 1, order.getOrderId(), order.getTotalPrice(), order.getUserId());
    }

    System.out.print("确认批量处理以上所有订单为已支付状态吗？(y/n): ");
    String confirm = scanner.nextLine();

    if ("y".equalsIgnoreCase(confirm)) {
        int successCount = 0;
        for (Order order : pendingOrders) {
            // 使用网络更新订单状态，确保状态同步到服务器
            Order updatedOrder = updateOrderStatusViaNetwork(order.getOrderId(), Order.OrderStatus.PAID);
            if (updatedOrder != null) {
                successCount++;
                System.out.printf("订单 %s 处理成功%n", order.getOrderId());
            } else {
                System.out.printf("订单 %s 处理失败%n", order.getOrderId());
            }
        }
        System.out.printf("批量处理完成，成功处理 %d 个订单。%n", successCount);
    } else {
        System.out.println("操作已取消。");
    }
}

/**
 * 批量设置为配送中
 */
private void batchSetShipping() {
    // 获取所有订单并筛选已支付订单（通过网络）
    List<Order> allOrders = getAllOrdersViaNetwork();
    List<Order> paidOrders = allOrders.stream()
        .filter(order -> order.getStatus() == Order.OrderStatus.PAID)
        .toList();

    if (paidOrders.isEmpty()) {
        System.out.println("没有已支付的订单。");
        return;
    }

    System.out.printf("找到 %d 个已支付订单:%n", paidOrders.size());
    for (int i = 0; i < paidOrders.size(); i++) {
        Order order = paidOrders.get(i);
        System.out.printf("%d. 订单ID: %s, 金额: ￥%.2f, 用户: %s%n",
            i + 1, order.getOrderId(), order.getTotalPrice(), order.getUserId());
    }

    System.out.print("确认批量处理以上所有订单为配送中状态吗？(y/n): ");
    String confirm = scanner.nextLine();

    if ("y".equalsIgnoreCase(confirm)) {
        int successCount = 0;
        for (Order order : paidOrders) {
            // 使用网络更新订单状态，确保状态同步到服务器
            Order updatedOrder = updateOrderStatusViaNetwork(order.getOrderId(), Order.OrderStatus.SHIPPING);
            if (updatedOrder != null) {
                successCount++;
                System.out.printf("订单 %s 处理成功%n", order.getOrderId());
            } else {
                System.out.printf("订单 %s 处理失败%n", order.getOrderId());
            }
        }
        System.out.printf("批量处理完成，成功处理 %d 个订单。%n", successCount);
    } else {
        System.out.println("操作已取消。");
    }
}

/**
 * 批量完成订单
 */
private void batchCompleteOrders() {
    // 获取所有订单并筛选配送中订单（通过网络）
    List<Order> allOrders = getAllOrdersViaNetwork();
    List<Order> shippingOrders = allOrders.stream()
        .filter(order -> order.getStatus() == Order.OrderStatus.SHIPPING)
        .toList();

    if (shippingOrders.isEmpty()) {
        System.out.println("没有配送中的订单。");
        return;
    }

    System.out.printf("找到 %d 个配送中订单:%n", shippingOrders.size());
    for (int i = 0; i < shippingOrders.size(); i++) {
        Order order = shippingOrders.get(i);
        System.out.printf("%d. 订单ID: %s, 金额: ￥%.2f, 用户: %s%n",
            i + 1, order.getOrderId(), order.getTotalPrice(), order.getUserId());
    }

    System.out.print("确认批量处理以上所有订单为已完成状态吗？(y/n): ");
    String confirm = scanner.nextLine();

    if ("y".equalsIgnoreCase(confirm)) {
        int successCount = 0;
        for (Order order : shippingOrders) {
            // 使用网络更新订单状态，确保状态同步到服务器
            Order updatedOrder = updateOrderStatusViaNetwork(order.getOrderId(), Order.OrderStatus.COMPLETED);
            if (updatedOrder != null) {
                successCount++;
                System.out.printf("订单 %s 处理成功%n", order.getOrderId());
            } else {
                System.out.printf("订单 %s 处理失败%n", order.getOrderId());
            }
        }
        System.out.printf("批量处理完成，成功处理 %d 个订单。%n", successCount);
    } else {
        System.out.println("操作已取消。");
    }
}

/**
 * 订单打印和导出功能
 */
private void printOrder() {
    System.out.print("请输入订单ID: ");
    String orderId = scanner.nextLine();

    Order order = orderService.findOrderById(orderId);
    if (order == null) {
        System.out.println("未找到该订单！");
        return;
    }

    System.out.println("\n--- 订单打印选项 ---");
    System.out.println("1. 屏幕显示订单详情");
    System.out.println("2. 导出订单为文本文件");
    System.out.print("请选择操作: ");

    int choice = readIntInput();

    switch (choice) {
        case 1:
            displayOrderForPrint(order);
            break;
        case 2:
            exportOrderToFile(order);
            break;
        default:
            System.out.println("无效的选项！");
    }
}

/**
 * 屏幕显示订单详情（打印格式）
 * @param order 订单对象
 */
private void displayOrderForPrint(Order order) {
    System.out.printf("\n%s%n", "=".repeat(50));
    System.out.println("           订单详情");
    System.out.println("=".repeat(50));
    System.out.printf("订单编号: %s%n", order.getOrderId());
    System.out.printf("订单状态: %s%n", order.getStatus().getDescription());
    System.out.printf("下单时间: %s%n", order.getCreateTime().format(
        java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    System.out.printf("客户ID: %s%n", order.getUserId());
    System.out.println("-".repeat(50));

    System.out.println("商品信息:");
    System.out.println("商品ID\t商品名称\t\t数量\t单价\t小计");
    System.out.println("-".repeat(50));

    double total = 0.0;
    for (Map.Entry<String, Integer> entry : order.getItems().entrySet()) {
        String productId = entry.getKey();
        Integer quantity = entry.getValue();
        Product product = productService.findProductById(productId);

        if (product != null) {
            double subtotal = product.getPrice() * quantity;
            System.out.printf("%s\t%-15s\t%d\t%.2f\t%.2f%n",
                product.getId(),
                product.getName().length() > 15 ? "%s...".formatted(product.getName().substring(0, 12)) : product.getName(),
                quantity,
                product.getPrice(),
                subtotal);
            total += subtotal;
        }
    }

    System.out.println("-".repeat(50));
    System.out.printf("总计: ￥%.2f%n", total);
    System.out.println("=".repeat(50));
    System.out.println("感谢您的购买！");
}

/**
 * 导出订单为文本文件
 * @param order 订单对象
 */
private void exportOrderToFile(Order order) {
    try {
        String filename = "order_%s.txt".formatted(order.getOrderId());
        FileWriter writer = new FileWriter(filename);

        writer.write("订单详情\n");
        writer.write("========\n");
        writer.write("订单编号: %s\n".formatted(order.getOrderId()));
        writer.write("订单状态: %s\n".formatted(order.getStatus().getDescription()));
        writer.write("下单时间: %s\n".formatted(order.getCreateTime().format(
                java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        writer.write("客户ID: %s\n".formatted(order.getUserId()));
        writer.write("------------------------------------------\n");

        writer.write("商品信息:\n");
        writer.write("商品ID\t商品名称\t\t数量\t单价\t小计\n");
        writer.write("------------------------------------------\n");

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : order.getItems().entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);

            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                writer.write(String.format("%s\t%-15s\t%d\t%.2f\t%.2f\n",
                    product.getId(),
                    product.getName().length() > 15 ? "%s...".formatted(product.getName().substring(0, 12)) : product.getName(),
                    quantity,
                    product.getPrice(),
                    subtotal));
                total += subtotal;
            }
        }

        writer.write("------------------------------------------\n");
        writer.write(String.format("总计: ￥%.2f\n", total));
        writer.write("==========================================\n");
        writer.write("感谢您的购买！\n");

        writer.close();
        System.out.printf("订单已成功导出到文件: %s%n", filename);
    } catch (IOException e) {
        System.out.printf("订单导出失败: %s%n", e.getMessage());
    }
}

/**
 * 获取订单配送状态描述
 * @param order 订单对象
 * @return 配送状态描述
 */
private String getOrderShippingStatus(Order order) {
    long daysSinceShipping = java.time.Duration.between(order.getUpdateTime(), java.time.LocalDateTime.now()).toDays();

    if (daysSinceShipping <= 1) {
        return "已揽收";
    } else if (daysSinceShipping <= 2) {
        return "运输中";
    } else if (daysSinceShipping <= 3) {
        return "派送中";
    } else {
        return "已完成";
    }
}

/**
 * 获取预计送达时间
 * @param order 订单对象
 * @return 预计送达时间
 */
private String getEstimatedDeliveryTime(Order order) {
    java.time.LocalDateTime estimatedTime = order.getUpdateTime().plusDays(3);
    return estimatedTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
}

/**
 * 生成模拟的物流步骤
 * @param order 订单对象
 * @return 物流步骤列表
 */
private List<String> generateShippingSteps(Order order) {
    List<String> steps = new ArrayList<>();
    steps.add(String.format("[%s] 订单已支付，等待发货",
               order.getUpdateTime().format(java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm"))));

    java.time.LocalDateTime packedTime = order.getUpdateTime().plusHours(2);
    steps.add(String.format("[%s] 商品已打包完成",
               packedTime.format(java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm"))));

    java.time.LocalDateTime shippedTime = order.getUpdateTime().plusHours(5);
    steps.add(String.format("[%s] 快递已揽收，运单号: SF%d",
               shippedTime.format(java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm")),
               Math.abs(order.getOrderId().hashCode())));

    java.time.LocalDateTime transitTime = order.getUpdateTime().plusDays(1);
    steps.add(String.format("[%s] 快件已到达【北京转运中心】",
               transitTime.format(java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm"))));

    java.time.LocalDateTime outTransitTime = order.getUpdateTime().plusDays(2);
    steps.add(String.format("[%s] 快件已从【北京转运中心】发出，下一站【朝阳区配送站】",
               outTransitTime.format(java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm"))));

    return steps;
}

/**
 * 订单取消和退款申请
 */
private void cancelAndRefundOrder() {
    System.out.print("请输入要取消和申请退款的订单ID: ");
    String orderId = scanner.nextLine();

    // 通过网络获取订单详情
    Order order = findOrderByIdViaNetwork(orderId);
    if (order == null) {
        System.out.println("未找到该订单！");
        return;
    }

    // 验证订单是否属于当前用户
    if (!order.getUserId().equals(currentUser.getUserId())) {
        System.out.println("您无权操作此订单！");
        return;
    }

    // 只有已支付和配送中的订单可以申请取消和退款
    if (order.getStatus() != Order.OrderStatus.PAID && order.getStatus() != Order.OrderStatus.SHIPPING) {
        System.out.println("只有已支付或配送中的订单才能申请取消和退款！");
        return;
    }

    System.out.println("订单详情:");
    System.out.println(order);

    System.out.print("确认要取消该订单并申请退款吗？(y/n): ");
    String confirm = scanner.nextLine();

    if (!"y".equalsIgnoreCase(confirm)) {
        System.out.println("操作已取消。");
        return;
    }

    // 通过网络更新订单状态为已取消
    Order updatedOrder = updateOrderStatusViaNetwork(orderId, Order.OrderStatus.CANCELLED);

    if (updatedOrder != null) {
        System.out.println("订单取消申请已提交，退款将在1-3个工作日内原路返回。");

        // 恢复商品库存
        restoreProductStock(order);
        System.out.println("相关商品库存已恢复。");
    } else {
        System.out.println("订单取消申请提交失败！");
    }
}

/**
 * 恢复订单中商品的库存
 * 注意：实际库存恢复已在服务器端处理，此方法仅用于显示信息
 * @param order 要恢复库存的订单
 */
private void restoreProductStock(Order order) {
    System.out.println("注意：商品库存恢复已在服务器端处理");
    for (Map.Entry<String, Integer> entry : order.getItems().entrySet()) {
        String productId = entry.getKey();
        Integer quantity = entry.getValue();

        // 仅显示信息，不实际修改库存（库存恢复已在服务器端处理）
        Product product = productService.findProductById(productId);
        if (product != null) {
            System.out.printf("商品 '%s' 将恢复 %d 件库存%n", product.getName(), quantity);
        }
    }
}


    /*
      控制订单状态流转 - 根据业务规则控制订单状态变更
     */
// 修改 controlOrderStatusFlow 方法，在订单完成时显示送达地址
/*
  控制订单状态流转 - 根据业务规则控制订单状态变更
 */
/**
 * 控制订单状态流转 - 根据业务规则控制订单状态变更（使用网络获取实时数据）
 */
private void controlOrderStatusFlow() {
    System.out.print("请输入订单ID: ");
    String orderId = scanner.nextLine();

    Order order = findOrderByIdViaNetwork(orderId);
    if (order == null) {
        System.out.printf("未找到订单：%s%n", orderId);
        return;
    }

    System.out.printf("当前订单状态：%s%n", order.getStatus());

    // 根据当前状态显示可选的下一状态
    showValidStatusTransitions(order);
}

  /**
 * 显示有效的状态转换选项
 * @param order 订单对象
 */
private void showValidStatusTransitions(Order order) {
    Order.OrderStatus currentStatus = order.getStatus();
    System.out.println("\n--- 可选状态转换 ---");

    List<Order.OrderStatus> validTransitions = new ArrayList<>();

    switch (currentStatus) {
        case PENDING_PAYMENT:
            System.out.println("1. 已付款 (PAID)");
            validTransitions.add(Order.OrderStatus.PAID);
            System.out.println("2. 已取消 (CANCELLED)");
            validTransitions.add(Order.OrderStatus.CANCELLED);
            break;
        case PAID:
            System.out.println("1. 配送中 (SHIPPING)");
            validTransitions.add(Order.OrderStatus.SHIPPING);
            System.out.println("2. 已取消 (CANCELLED)");
            validTransitions.add(Order.OrderStatus.CANCELLED);
            break;
        case SHIPPING:
            System.out.println("1. 已完成 (COMPLETED)");
            validTransitions.add(Order.OrderStatus.COMPLETED);
            break;
        case COMPLETED:
            System.out.println("订单已完成，无法更改状态。");
            return;
        case CANCELLED:
            System.out.println("订单已取消，无法更改状态。");
            return;
    }

    if (validTransitions.isEmpty()) {
        return;
    }

    System.out.print("请选择要转换到的状态 (输入对应数字): ");
    int choice = readIntInput();

    if (choice < 1 || choice > validTransitions.size()) {
        System.out.println("无效的选择！");
        return;
    }

    Order.OrderStatus newStatus = validTransitions.get(choice - 1);
    // 使用网络更新订单状态，确保状态同步到服务器
    Order updatedOrder = updateOrderStatusViaNetwork(order.getOrderId(), newStatus);

    if (updatedOrder != null) {
        System.out.println("订单状态更新成功！");
        System.out.printf("更新后的订单信息：%s%n", updatedOrder);

        // 如果订单已完成，从购物车中移除相关商品
        if (newStatus == Order.OrderStatus.COMPLETED) {
            removeFromCartIfCompleted(updatedOrder);
        }
    } else {
        System.out.println("订单状态更新失败！");
    }
}

/**
 * 当订单完成时，从购物车中移除相关商品
 * @param order 已完成的订单
 */
private void removeFromCartIfCompleted(Order order) {
    // 从购物车中移除已完成订单中的商品
    for (Map.Entry<String, Integer> entry : order.getItems().entrySet()) {
        String productId = entry.getKey();
        // 检查购物车中是否包含该商品
        if (shoppingCart.containsKey(productId)) {
            // 移除购物车中的商品
            shoppingCart.remove(productId);
            System.out.printf("商品 %s 已从购物车中移除%n", productId);
        }
    }
}

    /**
     * 查看所有订单
     */
private void viewAllOrders() {
    List<Order> allOrders = getAllOrdersViaNetwork();

    if (allOrders.isEmpty()) {
        System.out.println("暂无订单。");
        return;
    }

    // 按创建时间倒序排列
    allOrders.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));

    System.out.println("\n--- 所有订单列表 ---");
    System.out.println("订单ID              | 用户ID    | 总价      | 状态     | 创建时间");
    System.out.println("------------------------------------------------------------------------");
    for (Order order : allOrders) {
        System.out.printf("%-20s| %-10s| ¥%-9.2f| %-8s| %s%n",
            order.getOrderId(),
            order.getUserId(),
            order.getTotalPrice(),
            order.getStatus().getDescription(),
            order.getCreateTime().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
        );
    }
}
/**
 * 按状态筛选订单
 */
private void filterOrdersByStatus() {
    System.out.println("\n请选择订单状态:");
    System.out.println("1. 待付款");
    System.out.println("2. 已付款");
    System.out.println("3. 配送中");
    System.out.println("4. 已完成");
    System.out.println("5. 已取消");
    System.out.print("请输入您的选择: ");

    int statusChoice = readIntInput();
    Order.OrderStatus selectedStatus;
    String statusName;

    switch (statusChoice) {
        case 1:
            selectedStatus = Order.OrderStatus.PENDING_PAYMENT;
            statusName = "待付款";
            break;
        case 2:
            selectedStatus = Order.OrderStatus.PAID;
            statusName = "已付款";
            break;
        case 3:
            selectedStatus = Order.OrderStatus.SHIPPING;
            statusName = "配送中";
            break;
        case 4:
            selectedStatus = Order.OrderStatus.COMPLETED;
            statusName = "已完成";
            break;
        case 5:
            selectedStatus = Order.OrderStatus.CANCELLED;
            statusName = "已取消";
            break;
        default:
            System.out.println("无效选择！");
            return;
    }

    // 获取所有订单并筛选
    List<Order> allOrders = getAllOrdersViaNetwork();
    List<Order> filteredOrders = allOrders.stream()
        .filter(order -> order.getStatus() == selectedStatus)
        .collect(java.util.stream.Collectors.toList());

    if (filteredOrders.isEmpty()) {
        System.out.printf("没有状态为'%s'的订单。\n", statusName);
        return;
    }

    // 按创建时间倒序排列
    filteredOrders.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));

    System.out.printf("\n--- 状态为'%s'的订单 ---\n", statusName);
    System.out.println("订单ID              | 用户ID    | 总价      | 创建时间");
    System.out.println("------------------------------------------------------------");
    for (Order order : filteredOrders) {
        System.out.printf("%-20s| %-10s| ¥%-9.2f| %s%n",
            order.getOrderId(),
            order.getUserId(),
            order.getTotalPrice(),
            order.getCreateTime().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
        );
    }
}

/**
 * 处理订单取消请求（客户功能）
 */
private void cancelOrder() {
    System.out.print("请输入要取消的订单ID: ");
    String orderId = scanner.nextLine();

    // 通过网络获取订单详情
    Order order = findOrderByIdViaNetwork(orderId);
    if (order == null) {
        System.out.println("未找到该订单！");
        return;
    }

    // 验证订单是否属于当前用户
    if (!order.getUserId().equals(currentUser.getUserId())) {
        System.out.println("您无权操作此订单！");
        return;
    }

    // 检查订单状态是否允许取消
    if (order.getStatus() != Order.OrderStatus.PENDING_PAYMENT &&
        order.getStatus() != Order.OrderStatus.PAID &&
        order.getStatus() != Order.OrderStatus.SHIPPING) {
        System.out.println("该订单状态不允许取消！");
        return;
    }

    System.out.println("订单详情:");
    System.out.println(order);

    System.out.print("确认要取消该订单吗？(y/n): ");
    String confirm = scanner.nextLine();

    if (!"y".equalsIgnoreCase(confirm)) {
        System.out.println("操作已取消。");
        return;
    }

    // 通过网络更新订单状态为已取消
    Order updatedOrder = updateOrderStatusViaNetwork(orderId, Order.OrderStatus.CANCELLED);

    if (updatedOrder != null) {
        System.out.println("订单取消成功！");

        // 如果订单已支付，提示将退款
        if (order.getStatus() == Order.OrderStatus.PAID ||
            order.getStatus() == Order.OrderStatus.SHIPPING) {
            System.out.println("退款将在1-3个工作日内原路返回。");
        }

        // 恢复商品库存（提示信息）
        restoreProductStock(order);
    } else {
        System.out.println("订单取消失败！");
    }
}

/**
 * 管理员查看订单详情（使用网络获取实时数据）
 */
private void viewOrderDetailsAdmin() {
    System.out.print("请输入订单ID: ");
    String orderId = scanner.nextLine();

    Order order = findOrderByIdViaNetwork(orderId);
    if (order == null) {
        System.out.println("未找到该订单！");
        return;
    }

    System.out.println("订单详情:");
    System.out.println(order);
}



/**
 * 管理员修改订单状态
 */
private void updateOrderStatusAdmin() {
    System.out.print("请输入订单ID: ");
    String orderId = scanner.nextLine();

    // 获取所有订单来查找指定订单
    List<Order> allOrders = getAllOrdersViaNetwork();
    Order order = null;
    for (Order o : allOrders) {
        if (o.getOrderId().equals(orderId)) {
            order = o;
            break;
        }
    }

    if (order == null) {
        System.out.println("未找到该订单！");
        return;
    }

    System.out.printf("当前订单状态: %s%n", order.getStatus().getDescription());
    System.out.println("\n请选择新的订单状态:");
    System.out.println("1. 待付款");
    System.out.println("2. 已付款");
    System.out.println("3. 配送中");
    System.out.println("4. 已完成");
    System.out.println("5. 已取消");
    System.out.print("请输入您的选择: ");

    int statusChoice = readIntInput();
    Order.OrderStatus newStatus;
    String statusName;

    switch (statusChoice) {
        case 1:
            newStatus = Order.OrderStatus.PENDING_PAYMENT;
            statusName = "待付款";
            break;
        case 2:
            newStatus = Order.OrderStatus.PAID;
            statusName = "已付款";
            break;
        case 3:
            newStatus = Order.OrderStatus.SHIPPING;
            statusName = "配送中";
            break;
        case 4:
            newStatus = Order.OrderStatus.COMPLETED;
            statusName = "已完成";
            break;
        case 5:
            newStatus = Order.OrderStatus.CANCELLED;
            statusName = "已取消";
            break;
        default:
            System.out.println("无效选择！");
            return;
    }

    Order updatedOrder = updateOrderStatusViaNetwork(orderId, newStatus);
    if (updatedOrder != null) {
        System.out.println("订单状态更新成功！");
        System.out.printf("订单 %s 状态已更新为: %s%n", orderId, statusName);
    } else {
        System.out.println("订单状态更新失败！");
    }
}


/**
 * 按用户筛选订单
 */
private void filterOrdersByUser() {
    System.out.print("请输入用户ID: ");
    String userId = scanner.nextLine();

    List<Order> userOrders = orderService.getOrdersByUserId(userId);

    if (userOrders.isEmpty()) {
        System.out.println("该用户没有订单。");
        return;
    }

    // 按创建时间倒序排列
    userOrders.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));

    System.out.printf("\n--- 用户'%s'的订单 ---\n", userId);
    System.out.println("订单ID              | 总价      | 状态     | 创建时间");
    System.out.println("--------------------------------------------------------");
    for (Order order : userOrders) {
        System.out.printf("%-20s| ¥%-9.2f| %-8s| %s%n",
            order.getOrderId(),
            order.getTotalPrice(),
            order.getStatus().getDescription(),
            order.getCreateTime().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
        );
    }
}

    /**
     * 更新订单状态
     */
    private void updateOrderStatus() {
        System.out.print("请输入订单ID: ");
        String orderId = scanner.nextLine();

        // 先从网络获取订单信息，确保获取最新状态
        Order order = findOrderByIdViaNetwork(orderId);
        if (order == null) {
            System.out.printf("未找到订单：%s%n", orderId);
            return;
        }

        System.out.printf("当前订单状态：%s%n", order.getStatus());
        System.out.println("\n--- 可选状态 ---");

        // 显示合法的状态转换选项
        Order.OrderStatus[] allStatuses = Order.OrderStatus.values();
        int validOptionCount = 0;
        Order.OrderStatus[] validStatuses = new Order.OrderStatus[allStatuses.length];

        for (Order.OrderStatus allStatus : allStatuses) {
            if (isValidStatusTransition(order.getStatus(), allStatus)) {
                validOptionCount++;
                validStatuses[validOptionCount - 1] = allStatus;
                System.out.printf("%d. %s%n", validOptionCount, allStatus);
            }
        }

        if (validOptionCount == 0) {
            System.out.println("当前状态无法进行任何转换！");
            return;
        }

        System.out.print("请选择新状态: ");
        int choice = readIntInput();
        if (choice < 1 || choice > validOptionCount) {
            System.out.println("无效的选择！");
            return;
        }

        Order.OrderStatus newStatus = validStatuses[choice - 1];
        try {
            // 使用网络更新订单状态，确保状态同步到服务器
            Order updatedOrder = updateOrderStatusViaNetwork(orderId, newStatus);
            if (updatedOrder != null) {
                System.out.println("订单状态更新成功！");
                System.out.printf("更新后的订单信息：%s%n", updatedOrder);
                
                // 如果订单被取消，需要恢复库存
                if (newStatus == Order.OrderStatus.CANCELLED) {
                    restoreProductStock(order);
                    System.out.println("相关商品库存已恢复。");
                }
            } else {
                System.out.println("订单状态更新失败！");
            }
        } catch (IllegalArgumentException e) {
            System.out.printf("状态更新失败：%s%n", e.getMessage());
        }
    }
    
    /**
     * 验证订单状态流转是否合法（客户端版本）
     */
    private boolean isValidStatusTransition(Order.OrderStatus currentStatus, Order.OrderStatus newStatus) {
        if (currentStatus == newStatus) {
            return false;
        }

        return switch (currentStatus) {
            case PENDING_PAYMENT -> newStatus == Order.OrderStatus.PAID || newStatus == Order.OrderStatus.CANCELLED;
            case PAID -> newStatus == Order.OrderStatus.SHIPPING || newStatus == Order.OrderStatus.CANCELLED;
            case SHIPPING -> newStatus == Order.OrderStatus.COMPLETED;
            default -> false;
        };
    }

    /**
 * 查看订单详情
 */
private void viewOrderDetails() {
    System.out.print("请输入订单ID: ");
    String orderId = scanner.nextLine();

    Order order = findOrderByIdViaNetwork(orderId);
    if (order == null) {
        System.out.println("未找到该订单！");
        return;
    }

    // 验证订单是否属于当前用户
    if (!order.getUserId().equals(currentUser.getUserId())) {
        System.out.println("您无权查看此订单！");
        return;
    }

    System.out.println("\n--- 订单详情 ---");
    System.out.println(order);
}

    /**
     * 商品分类管理功能
     */
    private void manageCategories() {
        while (true) {
            System.out.println("\n--- 商品分类管理 ---");
            System.out.println("1. 查看所有分类");
            System.out.println("2. 添加分类");
            System.out.println("3. 更新分类");
            System.out.println("4. 删除分类");
            System.out.println("5. 查看分类下的商品");
            System.out.println("6. 为商品添加分类");
            System.out.println("7. 从分类中移除商品");
            System.out.println("0. 返回上级菜单");
            System.out.print("请输入您的选择: ");

            int choice = readIntInput();

            switch (choice) {
                case 1:
                    viewAllCategories();
                    break;
                case 2:
                    addCategory();
                    break;
                case 3:
                    updateCategory();
                    break;
                case 4:
                    removeCategory();
                    break;
                case 5:
                    viewProductsByCategory();
                    break;
                case 6:
                    addProductToCategory();
                    break;
                case 7:
                    removeProductFromCategory();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效的选项！");
            }

            // 等待用户按键后继续
            System.out.println("\n按回车键继续...");
            scanner.nextLine();
        }
    }

    /**
     * 查看所有分类
     */
    private void viewAllCategories() {
        List<Category> categories = categoryService.getAllCategories();
        if (categories.isEmpty()) {
            System.out.println("暂无分类。");
            return;
        }

        System.out.println("\n--- 所有分类 ---");
        for (Category category : categories) {
            System.out.println(category.toString());
        }
    }

    /**
     * 添加分类
     */
    private void addCategory() {
        System.out.print("请输入分类ID: ");
        String categoryId = scanner.nextLine();

        System.out.print("请输入分类名称: ");
        String categoryName = scanner.nextLine();

        System.out.print("请输入分类描述(可选): ");
        String description = scanner.nextLine();

        Category category = new Category(categoryId, categoryName, description);
        boolean success = categoryService.addCategory(category);

        if (success) {
            System.out.println("分类添加成功！");
        } else {
            System.out.println("分类添加失败！可能分类ID已存在。");
        }
    }

    /**
     * 更新分类
     */
    private void updateCategory() {
        System.out.print("请输入要更新的分类ID: ");
        String categoryId = scanner.nextLine();

        Category category = categoryService.findCategoryById(categoryId);
        if (category == null) {
            System.out.printf("未找到分类：%s%n", categoryId);
            return;
        }

        System.out.printf("当前分类信息：%s%n", category);

        System.out.print("请输入新的分类名称(回车跳过): ");
        String categoryName = scanner.nextLine();
        if (categoryName.trim().isEmpty()) {
            categoryName = null;
        }

        System.out.print("请输入新的分类描述(回车跳过): ");
        String description = scanner.nextLine();
        if (description.trim().isEmpty()) {
            description = null;
        }

        boolean success = categoryService.updateCategory(categoryId, categoryName, description);
        if (success) {
            System.out.println("分类更新成功！");
            Category updatedCategory = categoryService.findCategoryById(categoryId);
            System.out.printf("更新后的分类信息：%s%n", updatedCategory.toString());
        } else {
            System.out.println("分类更新失败！");
        }
    }

    /**
     * 删除分类
     */
    private void removeCategory() {
        System.out.print("请输入要删除的分类ID: ");
        String categoryId = scanner.nextLine();

        Category category = categoryService.findCategoryById(categoryId);
        if (category == null) {
            System.out.printf("未找到分类：%s%n", categoryId);
            return;
        }

        System.out.printf("确定要删除分类 '%s' 吗？这将移除该分类与所有商品的关联。(y/n)%n", category.getCategoryName());
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm)) {
            boolean success = categoryService.removeCategory(categoryId);
            if (success) {
                System.out.println("分类删除成功！");
            } else {
                System.out.println("分类删除失败！");
            }
        } else {
            System.out.println("操作已取消。");
        }
    }

    /**
     * 查看分类下的商品
     */
    private void viewProductsByCategory() {
        System.out.print("请输入分类ID: ");
        String categoryId = scanner.nextLine();

        Category category = categoryService.findCategoryById(categoryId);
        if (category == null) {
            System.out.printf("未找到分类：%s%n", categoryId);
            return;
        }

        List<Product> products = categoryService.getProductsByCategory(categoryId);
        if (products.isEmpty()) {
            System.out.printf("分类 '%s' 下暂无商品。%n", category.getCategoryName());
            return;
        }

        System.out.printf("\n--- 分类 '%s' 下的商品 ---%n", category.getCategoryName());
        for (Product product : products) {
            System.out.println(product.toString());
        }
    }

    /**
     * 为商品添加分类
     */
    private void addProductToCategory() {
        System.out.print("请输入分类ID: ");
        String categoryId = scanner.nextLine();

        Category category = categoryService.findCategoryById(categoryId);
        if (category == null) {
            System.out.printf("未找到分类：%s%n", categoryId);
            return;
        }

        System.out.print("请输入商品ID: ");
        String productId = scanner.nextLine();

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.printf("未找到商品：%s%n", productId);
            return;
        }

        boolean success = categoryService.addProductToCategory(categoryId, productId);
        if (success) {
            System.out.printf("成功将商品 '%s' 添加到分类 '%s'%n", product.getName(), category.getCategoryName());
        } else {
            System.out.println("添加失败！");
        }
    }

    /**
     * 从分类中移除商品
     */
    private void removeProductFromCategory() {
        System.out.print("请输入分类ID: ");
        String categoryId = scanner.nextLine();

        Category category = categoryService.findCategoryById(categoryId);
        if (category == null) {
            System.out.printf("未找到分类：%s%n", categoryId);
            return;
        }

        System.out.print("请输入商品ID: ");
        String productId = scanner.nextLine();

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.printf("未找到商品：%s%n", productId);
            return;
        }
        boolean success = categoryService.removeProductFromCategory(categoryId, productId);
        if (success) {
            System.out.printf("成功从分类 '%s' 中移除商品 '%s'%n", category.getCategoryName(), product.getName());
        } else {
            System.out.println("移除失败！商品可能不在该分类中。");
        }
    }
    // 实现按分类浏览的方法
    private void browseProductsByCategory() {
        System.out.println("\n--- 按分类浏览商品 ---");
        List<Category> categories = categoryService.getAllCategories();

        if (categories.isEmpty()) {
            System.out.println("暂无商品分类。");
            return;
        }
        System.out.println("请选择分类:");
        for (int i = 0; i < categories.size(); i++) {
            System.out.printf("%d. %s%n", i + 1, categories.get(i).getCategoryName());
        }
        System.out.printf("%d. 返回上级菜单%n", categories.size() + 1);
        System.out.print("请输入您的选择: ");

        int choice = readIntInput();
        if (choice < 1 || choice > categories.size() + 1) {
            System.out.println("无效的选项！");
            return;
        }
        if (choice == categories.size() + 1) {
            return; // 返回上级菜单
        }

        Category selectedCategory = categories.get(choice - 1);
        List<Product> products = categoryService.getProductsByCategory(selectedCategory.getCategoryId());

        if (products.isEmpty()) {
            System.out.println("该分类下暂无商品。");
        } else {
            System.out.printf("\n[%s] 分类下的商品:%n", selectedCategory.getCategoryName());
            for (Product product : products) {
                System.out.println(product.toString());
            }
        }
    }
// 在 ConsoleShop 类中添加以下两个方法
/*
  读取隐藏密码输入
  @param prompt 提示信息
 * @return 用户输入的密码
 */
/**
 * 读取隐藏密码输入（带星号显示）
 * @param prompt 提示信息
 * @return 用户输入的密码
 */
private String readPassword(String prompt) {
    Console console = System.console();
    if (console != null) {
        // 在支持的环境中使用系统控制台
        char[] passwordArray = console.readPassword(prompt);
        return new String(passwordArray);
    } else {
        // 回退方案：手动实现星号显示
        System.out.print(prompt);
        StringBuilder password = new StringBuilder();
        try {
            while (true) {
                int ch = System.in.read();
                if (ch == '\r' || ch == '\n') {
                    System.out.println();
                    break;
                } else if (ch == 127 || ch == 8) { // 退格键
                    if (!password.isEmpty()) {
                        password.deleteCharAt(password.length() - 1);
                        System.out.print("\b \b");
                    }
                } else {
                    password.append((char) ch);
                    System.out.print("*");
                }
            }
        } catch (IOException e) {
            System.out.println();
        }
        return password.toString();
    }
}
/**
 * 验证邮箱格式是否正确
 * @param email 邮箱地址
 * @return 格式正确返回false（无错误），否则返回true（有错误）
 */
private boolean isValidEmail(String email) {
    if (email == null || email.isEmpty()) {
        return false; // 空邮箱视为有效（可选）
    }

    String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(emailRegex);
    return !pattern.matcher(email).matches(); // 返回false表示格式正确，true表示格式错误
}
    /**
     * 通过网络为商品添加标签
     * @param productId 商品ID
     * @param tag 标签
     * @return 是否添加成功
     */
    private boolean addTagToProductViaNetwork(String productId, String tag) {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 发送添加标签请求
            String request = "ADD TAG TO PRODUCT:%s:%s".formatted(productId, tag);
            output.writeObject(request);
            output.flush();

            // 读取响应
            Object response = input.readObject();
            if (response instanceof String message) {
                if (message.contains("成功")) {
                    return true;
                } else {
                    System.err.println(message);
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.printf("网络错误: %s%n", e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭连接时出错: %s%n", e.getMessage());
                }
            }
        }
        return false;
    }

    /**
     * 通过网络从商品中移除标签
     * @param productId 商品ID
     * @param tag 标签
     * @return 是否移除成功
     */
    private boolean removeTagFromProductViaNetwork(String productId, String tag) {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 发送移除标签请求
            String request = "REMOVE TAG FROM PRODUCT:%s:%s".formatted(productId, tag);
            output.writeObject(request);
            output.flush();

            // 读取响应
            Object response = input.readObject();
            if (response instanceof String message) {
                if (message.contains("成功")) {
                    return true;
                } else {
                    System.err.println(message);
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.printf("网络错误: %s%n", e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭连接时出错: %s%n", e.getMessage());
                }
            }
        }
        return false;
    }

    /**
     * 通过网络更新商品标签
     * @param productId 商品ID
     * @param tags 新的标签集合
     * @return 更新后的商品对象，失败返回null
     */
    private Product updateProductTagsViaNetwork(String productId, Set<String> tags) {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            Object response = getObject(productId, tags, socket);
            if (response instanceof Product) {
                return (Product) response;
            } else if (response instanceof String) {
                System.err.printf("更新失败: %s%n", response);
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.printf("网络错误: %s%n", e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭连接时出错: %s%n", e.getMessage());
                }
            }
        }
        return null;
    }

    private static Object getObject(String productId, Set<String> tags, Socket socket) throws IOException, ClassNotFoundException {
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

        // 构建标签字符串
        StringBuilder tagsStr = new StringBuilder();
        boolean first = true;
        for (String tag : tags) {
            if (!first) {
                tagsStr.append(",");
            }
            tagsStr.append(tag);
            first = false;
        }

        // 发送更新标签请求
        String request = "UPDATE PRODUCT TAGS:%s:%s".formatted(productId, tagsStr.toString());
        output.writeObject(request);
        output.flush();

        // 读取响应
        return input.readObject();
    }

    /**
     * 通过网络获取所有商品
     * @return 商品列表
     */
    private List<Product> getAllProductsViaNetwork() {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());

            // 发送获取所有商品的请求
            output.writeObject("GET ALL PRODUCTS");
            output.flush();

            // 读取响应
            Object response = input.readObject();
            if (response instanceof List) {
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) response;
                return products;
            } else {
                System.err.printf("获取商品列表失败: %s%n", response);
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.printf("网络错误: %s%n", e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.printf("关闭连接时出错: %s%n", e.getMessage());
                }
            }
        }
        return new ArrayList<>();
    }
    /**
     * 通过网络获取商品信息
     * @param productId 商品ID
     * @return 商品对象，如果未找到返回null
     */
    private Product getProductByIdViaNetwork(String productId) {
        try {
            // 获取所有商品
            List<Product> allProducts = getAllProductsViaNetwork();
            if (allProducts != null) {
                // 查找指定ID的商品
                for (Product product : allProducts) {
                    if (product.getId().equals(productId)) {
                        return product;
                    }
                }
            }
        } catch (Exception e) {
            System.err.printf("获取商品详情失败: %s%n", e.getMessage());
        }
        return null;
    }

    public static void main() {
        new EStoreClient().start();
    }
}
